package modulos;

import static javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
import static javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER;
import static javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
import static javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER;

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyVetoException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Random;
import java.util.Vector;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JViewport;
import javax.swing.ListSelectionModel;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingWorker;
import javax.swing.Timer;
import javax.swing.border.Border;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

import org.joda.time.DateTime;

import plantable.AttributiveCellRenderer;
import plantable.CellSpan;
import plantable.MultiSpanCellTable;
import plantable.TableModelAttributiveCell;
import auxiliary.Constants;
import auxiliary.Database;
import auxiliary.GercoPlaneacion;
import auxiliary.IndexedList;
import auxiliary.Planner;
import auxiliary.Verifier;

public class PanelConfirmar extends JPanel implements ActionListener
,PropertyChangeListener {

	private static final long serialVersionUID = 1L;
	JProgressBar pbar;
	int counter;
	JTable jt;
	MultiSpanCellTable mt;
	TableModelPlan ftm;
	PanelConfirmar panel;
	Border raisedbevel;
	TableModelAttributiveCell ml;
	CellSpan cellAtt;
	ArrayList<String> years;
	JInternalFrame gridFrame;
	JPanel buttonPanel, glassPanel, gridPanel;
	String[] months, days;
	int[] monthDays;
	int currentMonth, currentYear;
	JPanel cards, backPanel, backPanel2, labelPanel, panelErrorActualizacionPendiente;
	JLabel label;
	JComboBox yearCombo, daysCombo, monthsCombo;
	ImageIcon imageicon, redicon, greenicon, add, delete, modify, verificar,database,deshacer,planicon;
	JLabel imagelabel;
	JButton mostrarButton, agregarloteButton, eliminarloteButton, modificarloteButton, verificarPlanButton,databaseButton,deshacerButton;
	Database db;
	Planner plan;
	String month, year;
	DateTime day;
	int dayselected;
	JScrollPane tablescrollpane;
	JViewport jv;
	boolean show;
	JTable headerColumn;
	String selectedradio;
	JPanel radioPanel;
	ArrayList<ArrayList<String>> listOfMensuales;
	Verifier verifyplan;
	ProgressMonitor progdialog;
	Task task;
	boolean changestatus;
	ArrayList<JRadioButton> radiobuttons;
	ArrayList<JRadioButton> copyradiobuttons;
	ButtonGroup group;
	Planner tempPlan;
	ConfirmarDia temp;
	GercoPlaneacion parent;


	class Task extends SwingWorker<Void, Void> {
		/*
		 * Main task. Executed in background thread.
		 */
		DateTime day;
		boolean valid;
		Verifier verifyplan;
		int type;
		int dayselected;
		String month, year;

		Task(int day,int dayselected, String month, String year, String type) {
			boolean valid = true;
			this.dayselected = dayselected;
			this.day = new DateTime(Integer.valueOf(year), Constants.monthsmap.get(month), day, 0, 0) ;
			this.month = month;
			this.year = year;
			if(type.equals("verificar"))
				this.type = 1;
			else if(type.equals("actualizar"))
				this.type = 2;
			else if(type.equals("confirmar"))
				this.type = 3;

		}

		public synchronized Void doInBackground() {
			@SuppressWarnings("unused")
			Random random = new Random();
			int progress = 0;
			// Initialize progress property.
			setProgress(0);
			if(type == 1) {
				verifyplan = new Verifier(plan,day);
				verifyplan.start();
			}
			else if(type == 2) {
				plan = new Planner(day.getDayOfMonth(), month, year,"actualizar",dayselected);
				plan.start();
			}
			else if(type == 3) {
				temp = new ConfirmarDia(day,dayselected,month,year,plan);
				temp.start();
			}

			while (progress < 108) {
				// Sleep for up to one second.
				try {
					Thread.sleep(/* random.nextInt(1000) */100);
				} catch (InterruptedException ignore) {
				}
				// Make random progress.

				// progress += random.nextInt(10);
				if(type==1)
					progress = verifyplan.getStatus();
				else if(type==2)
					progress = plan.getCurrTime();
				else if(type==3)
					progress = temp.getConfirmarCount();

				setProgress(Math.min(progress, 110));
				////System.out.println("cambio el progress");
			}
			// progdialog.dispose();
			return null;
		}

		/*
		 * Executed in event dispatching thread
		 */
		@Override
		public void done() {
			progdialog.dispose();
			setProgress(0);
			Toolkit.getDefaultToolkit().beep();
			// startButton.setEnabled(true);
			setCursor(null); // turn off the wait cursor
			// taskOutput.append("Done!\n");

			if(type==1)
				valid = verifyplan.getValidity();


		}

		public String getError() {
			return verifyplan.getErrorString();
		}
	}

	class ProgressMonitor extends JDialog {

		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;
		Container contentPane;
		Timer timer;

		public ProgressMonitor(JFrame parent) {
			super(parent, "Progreso");
			counter = 0;

			pbar = new JProgressBar(0, 100);

			contentPane = getContentPane();

			contentPane.add(BorderLayout.CENTER, pbar);
			contentPane.add(BorderLayout.NORTH, new JLabel("Progreso de tarea..."));
			this.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
			// dlg.setSize(300, 75);

			// Fire a timer every once in a while to update the progress.

			// pack();
			// setVisible(true);

		}
	}

	public PanelConfirmar(GercoPlaneacion parent) {
		//super(parent);
		this.parent = parent;
		changestatus = false;
		show = false;
		db = new Database();
		dayselected = 0;

		// lock = new Lock();
		selectedradio = "0";
		progdialog = new ProgressMonitor(Constants.getParentFrame(this));
		currentMonth = Calendar.getInstance().get(Calendar.MONTH);
		currentYear = Calendar.getInstance().get(Calendar.YEAR);
		months = new String[] { "Ene", "Feb", "Mar", "Abr", "May", "Jun",
				"Jul", "Ago", "Sep", "Oct", "Nov", "Dic" };
		years = new ArrayList<String>();
		monthDays = new int[] { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
		days = new String[] { "Lunes", "Martes", "Miercoles", "Jueves", "Viernes", "Sabado" };
		// progdialog.setVisible(false);

		URL imgURL = ClassLoader.getSystemResource("images/back.png");
		Image image = Toolkit.getDefaultToolkit().getImage(imgURL);

		// String dir = System.getProperty("user.dir");
		imageicon = new ImageIcon(image);
		imagelabel = new JLabel(imageicon);

		imgURL = ClassLoader.getSystemResource("images/red.png");
		image = Toolkit.getDefaultToolkit().getImage(imgURL);


		redicon = new ImageIcon(image);

		Image img = redicon.getImage();  
		Image newimg = img.getScaledInstance(20, 20,  java.awt.Image.SCALE_SMOOTH);  
		redicon = new ImageIcon(newimg);

		imgURL = ClassLoader.getSystemResource("images/green.png");
		image = Toolkit.getDefaultToolkit().getImage(imgURL);

		greenicon = new ImageIcon(image);

		img = greenicon.getImage();  
		newimg = img.getScaledInstance(20, 20,  java.awt.Image.SCALE_SMOOTH);  
		greenicon = new ImageIcon(newimg);

		imgURL = ClassLoader.getSystemResource("images/add.png");
		image = Toolkit.getDefaultToolkit().getImage(imgURL);

		add = new ImageIcon(image);

		img = add.getImage();  
		newimg = img.getScaledInstance(20, 20,  java.awt.Image.SCALE_SMOOTH);  
		add = new ImageIcon(newimg);

		imgURL = ClassLoader.getSystemResource("images/delete.png");
		image = Toolkit.getDefaultToolkit().getImage(imgURL);

		delete = new ImageIcon(image);

		img = delete.getImage();  
		newimg = img.getScaledInstance(20, 20,  java.awt.Image.SCALE_SMOOTH);  
		delete = new ImageIcon(newimg);

		imgURL = ClassLoader.getSystemResource("images/modify.png");
		image = Toolkit.getDefaultToolkit().getImage(imgURL);

		modify = new ImageIcon(image);

		img = modify.getImage();  
		newimg = img.getScaledInstance(20, 20,  java.awt.Image.SCALE_SMOOTH);  
		modify = new ImageIcon(newimg);

		imgURL = ClassLoader.getSystemResource("images/verify.png");
		image = Toolkit.getDefaultToolkit().getImage(imgURL);

		verificar = new ImageIcon(image);

		img = verificar.getImage();  
		newimg = img.getScaledInstance(20, 20,  java.awt.Image.SCALE_SMOOTH);  
		verificar = new ImageIcon(newimg);

		imgURL = ClassLoader.getSystemResource("images/database.png");
		image = Toolkit.getDefaultToolkit().getImage(imgURL);

		database = new ImageIcon(image);

		img = database.getImage();  
		newimg = img.getScaledInstance(20, 20,  java.awt.Image.SCALE_SMOOTH);  
		database = new ImageIcon(newimg);

		imgURL = ClassLoader.getSystemResource("images/undo.png");
		image = Toolkit.getDefaultToolkit().getImage(imgURL);

		deshacer = new ImageIcon(image);

		img = deshacer.getImage();  
		newimg = img.getScaledInstance(20, 20,  java.awt.Image.SCALE_SMOOTH);  
		deshacer = new ImageIcon(newimg);

		imgURL = ClassLoader.getSystemResource("images/plan.png");
		image = Toolkit.getDefaultToolkit().getImage(imgURL);

		planicon = new ImageIcon(image);

		img = planicon.getImage();  
		newimg = img.getScaledInstance(20, 20,  java.awt.Image.SCALE_SMOOTH);  
		planicon = new ImageIcon(newimg);

		for (int i = 0; i < 20; i++) {
			years.add(Integer.toString(2011 + i));
		}


		yearCombo = new JComboBox(Constants.singleArrayListToString(years));
		monthsCombo = new JComboBox(Constants
				.getStartWeek(String.valueOf((Integer
						.valueOf((String) yearCombo.getSelectedItem())))));



		daysCombo = new JComboBox(days);
		daysCombo.setActionCommand("daysComboChanged");
		daysCombo.setEnabled(false);

		monthsCombo.setActionCommand("monthsComboChanged");

		yearCombo.addActionListener(this);
		daysCombo.addActionListener(this);
		monthsCombo.addActionListener(this);

		panel = this;

		mostrarButton = new JButton("Mostrar");
		mostrarButton.setActionCommand(Constants.PLAN_MOSTRAR);
		mostrarButton.addActionListener(this);

		buttonPanel = new JPanel();
		buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));

		glassPanel = new JPanel()  
		{  
			/**
			 * 
			 */
			private static final long serialVersionUID = 1L;

			public void paintComponent(Graphics g)  
			{  
				//Set the color to with red with a 50% alpha  
				g.setColor(new Color(0, 0, 0, 0.5f));  

				//Fill a rectangle with the 50% red color  
				g.fillRect(0, 0, this.getWidth(), this.getHeight());  
			}  
		};  

		////System.out.println("toplevelancestor" + parent.getName());
		glassPanel.setOpaque(false);  



		//glassPanel.setVisible(true); 

		gridPanel = new JPanel(new BorderLayout());
		gridFrame = new JInternalFrame();
		//gridFrame.setBorder(null);
		gridFrame.setGlassPane(glassPanel);
		gridPanel.add(gridFrame);

		JPanel topPanel = new JPanel(new BorderLayout());

		// yearCombo = new JComboBox(Constants.singleArrayListToString(years));
		// monthsCombo = new JComboBox(months);
		// daysCombo = new JComboBox(Constants.singleArrayListToString(days
		// .get(currentMonth)));

		JPanel leftPanel = new JPanel(new BorderLayout());
		JPanel datePanel = new JPanel(new BorderLayout());
		JPanel mostrarPanel = new JPanel(new BorderLayout());

		leftPanel.add(datePanel, BorderLayout.CENTER);
		leftPanel.add(mostrarPanel, BorderLayout.EAST);

		topPanel.add(leftPanel, BorderLayout.EAST);

		datePanel.add(daysCombo, BorderLayout.WEST);
		datePanel.add(monthsCombo, BorderLayout.CENTER);
		datePanel.add(yearCombo, BorderLayout.EAST);

		leftPanel.add(mostrarButton, BorderLayout.EAST);

		cards = new JPanel(new CardLayout());
		backPanel = new JPanel(new BorderLayout());
		backPanel2 = new JPanel(new BorderLayout());
		panelErrorActualizacionPendiente = new JPanel(new BorderLayout());

		String labelText = "<html><B>Por favor seleccione una combinacion Semana/A&ntilde;o "
				+ "para ver plan para esa fecha</B>";
		String labelText2 = "<html><FONT COLOR=RED><B>No se ha creado lista de produccion para la fecha seleccionada</B></FONT>";
		JLabel textLabel = new JLabel(labelText, JLabel.CENTER);
		JLabel textLabel2 = new JLabel(labelText2, JLabel.CENTER);

		String textoErrorActualizacionPendiente = "<html><FONT COLOR=RED><B>Existe una actualizacion pendiente </B></FONT>";
		JLabel labelErrorActualizacionPendiente = new JLabel(textoErrorActualizacionPendiente, JLabel.CENTER);


		backPanel.add(textLabel, BorderLayout.CENTER);
		JPanel imagePanel = new JPanel(new BorderLayout());
		imagePanel.add(new JLabel(imageicon), BorderLayout.EAST);
		backPanel.add(imagePanel, BorderLayout.SOUTH);

		backPanel2.add(textLabel2, BorderLayout.CENTER);
		JPanel imagePanel2 = new JPanel(new BorderLayout());
		imagePanel2.add(new JLabel(imageicon), BorderLayout.EAST);
		backPanel2.add(imagePanel2, BorderLayout.SOUTH);

		panelErrorActualizacionPendiente.add(labelErrorActualizacionPendiente, BorderLayout.CENTER);
		imagePanel2 = new JPanel(new BorderLayout());
		imagePanel2.add(new JLabel(imageicon), BorderLayout.EAST);
		panelErrorActualizacionPendiente.add(imagePanel2, BorderLayout.SOUTH);

		cards.add(backPanel, Constants.PlanLabel.PANEL_INICIAL.toString());
		cards.add(backPanel2, Constants.PlanLabel.PANEL_ERROR_LISTA_NO_CREADA.toString());
		cards.add(panelErrorActualizacionPendiente, Constants.PlanLabel.PANEL_ERROR_ACTUALIZACION_PENDIENTE.toString());
		cards.add(gridPanel, Constants.PlanLabel.GRID_PANEL.toString());

		this.setLayout(new BorderLayout());
		this.add(topPanel, BorderLayout.NORTH);
		this.add(cards, BorderLayout.CENTER);

	}

	public void createPlan(String day, String month, String year,boolean changedays) {
		if(!changedays) {
			plan = new Planner(Integer.valueOf(day), month, year, "", dayselected);
			plan.start();

			while (plan.done == false) {
				try {
					// pbar.
					Thread.sleep(10);
					// task.firePropertyChange(day, month, year);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}

		show = plan.exists;

		ml = plan.ml;
		cellAtt = plan.cellAtt;

		/***
		 * adding table to gridpanel and showing it
		 */

		boolean previosconfirmadoscheck = false;
		boolean diaconfirmadoscheck = false;
		boolean currentdiaconfirmado = false;
		int dayselected = daysCombo.getSelectedIndex();
		int ultimodia = db.retrieveLastDiaConfirmado(Integer.valueOf(day),month,year);


		String message ="";

		if(!show) {
			message = "<html><FONT COLOR=RED><B>No se ha creado Plan para esta fecha </B></FONT>";
		}

		if((dayselected == 0 || dayselected == 5) && show) {

			if(ultimodia > dayselected+1) {
				previosconfirmadoscheck = true;
				diaconfirmadoscheck = true;
				message = "Dia ya ha sido confirmado si quiere cambiarlo debe cancelar confirmacion de dias futuros";
			}else if(ultimodia == dayselected+1) {
				previosconfirmadoscheck = true;

				if(dayselected == 5) {
					int monthindex = monthsCombo.getSelectedIndex();
					String array[] = ((String) monthsCombo.getSelectedItem()).split("/");
					String currentyear = ((String) yearCombo.getItemAt(yearCombo.getSelectedIndex()));

					if(monthindex == monthsCombo.getItemCount()) {

						String[] nextweeks = Constants.getStartWeek(String
								.valueOf(Integer.valueOf(currentyear)+1));
						String newarray[] = nextweeks[0].split("/");
						if(newarray[0].equals(array[0]) 
								&& newarray[1].equals(array[1])
								&& newarray[2].equals(array[2])) {
							newarray = nextweeks[1].split("/");
						}

						array = newarray.clone();
					}
					else {
						String[] nextweeks = Constants.getStartWeek(currentyear);
						array = nextweeks[monthsCombo.getSelectedIndex()+1].split("/");
					}

					int nextdia = db.retrieveIfSpecificDiaConfirmado(dayselected+1,Integer.valueOf(array[0]),array[1],array[2]);
					if(nextdia == 0) {
						diaconfirmadoscheck = false;	
						currentdiaconfirmado = true;
					}
					else {
						diaconfirmadoscheck = true;	
						message = "Dia ya ha sido confirmado si quiere cambiarlo debe cancelar confirmacion de dias futuros";	
					}

				}
				else {
					diaconfirmadoscheck = false;	
					currentdiaconfirmado = true;
				}
			}
			else if(dayselected == 0) {
				diaconfirmadoscheck = false;

				String array[] = ((String) monthsCombo.getSelectedItem()).split("/");

				int monthindex = monthsCombo.getSelectedIndex();
				if(monthindex == 0 && (yearCombo.getSelectedIndex() == 0)) {
					previosconfirmadoscheck = true;
				}
				else {
					if(monthindex == 0) {
						int previousyear = (Integer.valueOf((String) yearCombo.getItemAt(yearCombo.getSelectedIndex()-1)));
						String[] previousweeks = Constants.getStartWeek(String
								.valueOf(previousyear));

						String newarray[] = previousweeks[previousweeks.length-1].split("/");
						if(newarray[0].equals(array[0]) 
								&& newarray[1].equals(array[1])
								&& newarray[2].equals(array[2])) {
							//System.out.println("previous year has same starting week");
							newarray = previousweeks[previousweeks.length-2].split("/");
						}
						array = newarray.clone();
					}
					else {
						array = ((String) monthsCombo.getItemAt(monthsCombo.getSelectedIndex()-1)).split("/");
					}

					int lastday = Integer.valueOf(array[0]);
					String lastmonth = array[1];
					String lastyear = array[2];

					int confirmados = db.countWeekConfirmados(lastday,lastmonth,lastyear);

					if(confirmados == 6 || confirmados == 0) {
						previosconfirmadoscheck = true;
					} else{
						message = "No se puede confirmar dia porque dias previos de la semana anterior no han sido confirmados";
					}
				}
			}
			else if(ultimodia >= dayselected) {
				previosconfirmadoscheck = true;
				diaconfirmadoscheck = false;
			}
			else {
				previosconfirmadoscheck = false;
				diaconfirmadoscheck = false;
				message = "No se puede confirmar dia porque dias previos no han sido confirmados";
			}
		}
		else {
			if(ultimodia >  dayselected+1) {
				previosconfirmadoscheck = true;
				diaconfirmadoscheck = true;	
				message = "Dia ya ha sido confirmado si quiere cambiarlo debe cancelar confirmacion de dias futuros";
			}
			else if(ultimodia == dayselected+1) {
				previosconfirmadoscheck = true;
				diaconfirmadoscheck = false;	
				currentdiaconfirmado = true;
			}
			else if(ultimodia >= dayselected) {
				previosconfirmadoscheck = true;
				diaconfirmadoscheck = false;
			}
			else {
				previosconfirmadoscheck = false;
				diaconfirmadoscheck = false;
				message = "No se puede confirmar dia porque dias previos no han sido confirmados";
			}
		}

		if(show && previosconfirmadoscheck && !diaconfirmadoscheck ) {



			radiobuttons = new ArrayList<JRadioButton>();

			for (Integer i = 0; i < plan.loteids.size(); i++) {
				radiobuttons.add(new JRadioButton());
				radiobuttons.get(i).setSize(20, 20);
				radiobuttons.get(i).setName(plan.loteids.get(i).toString());
				radiobuttons.get(i).setActionCommand(Constants.SET_LOTE_INDEX);
				radiobuttons.get(i).addActionListener(this);

			}
			radiobuttons.get(0).setSelected(true);

			selectedradio = plan.loteids.get(0).toString();


			group = new ButtonGroup();
			radioPanel = new JPanel();
			radioPanel.setLayout(new BoxLayout(radioPanel, BoxLayout.Y_AXIS));

			radioPanel.add(Box.createRigidArea(new Dimension(10, 22)));

			for (int i = 0; i < plan.loteids.size(); i++) {
				group.add(radiobuttons.get(i));
				radioPanel.add(radiobuttons.get(i));
				radioPanel.add(Box.createRigidArea(new Dimension(10,42)));
			}

			buttonPanel = new JPanel();
			buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));

			agregarloteButton = new JButton("Agregar Lote",add);
			agregarloteButton.setActionCommand(Constants.AGREGAR_LOTE);
			agregarloteButton.addActionListener(this);

			modificarloteButton = new JButton("Modificar Lote",modify);
			modificarloteButton.setActionCommand(Constants.MODIFICAR_LOTE);
			modificarloteButton.addActionListener(this);

			eliminarloteButton = new JButton("Eliminar Lote",delete);
			eliminarloteButton.setActionCommand(Constants.ELIMINAR_LOTE);
			eliminarloteButton.addActionListener(this);

			verificarPlanButton = new JButton("Verificar",verificar);
			verificarPlanButton.setActionCommand(Constants.VERIFICAR_PLAN);
			verificarPlanButton.addActionListener(this);

			databaseButton = new JButton("Confirmar Dia",planicon);
			databaseButton.setActionCommand(Constants.CONFIRMAR_PLAN);
			databaseButton.addActionListener(this);
			databaseButton.setEnabled(false);
			//			
			//			deshacerButton = new JButton("Cambiar Dia",deshacer);
			//			deshacerButton.setActionCommand(Constants.DESHACER_PLAN);
			//			deshacerButton.addActionListener(this);


			gridPanel = new JPanel(new BorderLayout());
			gridFrame = new JInternalFrame();
			gridFrame.setClosable(false);
			gridFrame.setMaximizable(false);

			for(MouseListener listener : ((javax.swing.plaf.basic.BasicInternalFrameUI) gridFrame.getUI()).getNorthPane().getMouseListeners()){
				((javax.swing.plaf.basic.BasicInternalFrameUI) gridFrame.getUI()).getNorthPane().removeMouseListener(listener);
			}

			javax.swing.plaf.InternalFrameUI ifu= gridFrame.getUI();
			((javax.swing.plaf.basic.BasicInternalFrameUI)ifu).setNorthPane(null);

			try {
				gridFrame.setSelected(true);
			} catch (PropertyVetoException e) {
				e.printStackTrace();
			}
			gridFrame.setGlassPane(glassPanel);
			gridFrame.setVisible(true);
			//gridFrame.setEnabled(false);




			TableColumnModel cm = new DefaultTableColumnModel() {
				/**
				 * 
				 */
				private static final long serialVersionUID = 1L;
				boolean first = true;

				public void addColumn(TableColumn tc) {
					if (first) {
						first = false;
						return;
					}
					tc.setMinWidth(65);
					super.addColumn(tc);
				}
			};

			TableColumnModel rowHeaderModel = new DefaultTableColumnModel() {
				/**
				 * 
				 */
				private static final long serialVersionUID = 1L;
				boolean first = true;

				public void addColumn(TableColumn tc) {
					if (first) {
						tc.setMinWidth(225);
						tc.setMaxWidth(tc.getPreferredWidth());
						super.addColumn(tc);
						first = false;
					}
				}
			};



			mt = new MultiSpanCellTable(ml, cm);
			headerColumn = new JTable(ml, rowHeaderModel);
			headerColumn.setRowHeight(2);
			mt.setRowHeight(mt.getRowHeight() * 2);
			mt.createDefaultColumnsFromModel();
			headerColumn.createDefaultColumnsFromModel();

			mt.setSelectionModel(headerColumn.getSelectionModel());
			mt.setDefaultRenderer(Object.class, new AttributiveCellRenderer());

			headerColumn.setDefaultRenderer(Object.class,
					new AttributiveCellRenderer());
			headerColumn.setEnabled(false);
			headerColumn.setRowHeight(60);
			headerColumn.getTableHeader().setReorderingAllowed(false);

			mt.setEnabled(false);
			mt.setRowHeight(60);
			mt.getTableHeader().setReorderingAllowed(false);
			mt.getTableHeader().setResizingAllowed(false);


			JPanel produccionpanel = new JPanel(new BorderLayout());

			produccionpanel.add(headerColumn,BorderLayout.CENTER);
			produccionpanel.add(radioPanel,BorderLayout.WEST);

			jv = new JViewport();
			jv.setView(produccionpanel);
			jv.setPreferredSize(headerColumn.getMaximumSize());

			mt.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);


			tablescrollpane = new JScrollPane(mt);
			tablescrollpane.setRowHeader(jv);
			tablescrollpane.setCorner(ScrollPaneConstants.UPPER_LEFT_CORNER, headerColumn
					.getTableHeader());
			tablescrollpane.setPreferredSize(new Dimension(900, 450));

			buttonPanel.add(Box.createHorizontalGlue());
			buttonPanel.add(agregarloteButton, BorderLayout.EAST);
			buttonPanel.add(modificarloteButton, BorderLayout.EAST);
			buttonPanel.add(eliminarloteButton, BorderLayout.EAST);
			buttonPanel.add(verificarPlanButton, BorderLayout.EAST);
			buttonPanel.add(databaseButton, BorderLayout.EAST);
			//buttonPanel.add(Box.createHorizontalGlue());

			buttonPanel.add(Box.createHorizontalGlue());
			buttonPanel.add(imagelabel, BorderLayout.EAST);

			gridFrame.add(tablescrollpane,BorderLayout.CENTER);
			gridPanel.add(gridFrame, BorderLayout.CENTER);
			gridPanel.add(buttonPanel, BorderLayout.SOUTH);

			if(currentdiaconfirmado) {
				glassPanel.setVisible(true);

				if(tablescrollpane!=null) {
					tablescrollpane.setHorizontalScrollBarPolicy(HORIZONTAL_SCROLLBAR_NEVER);
					tablescrollpane.setVerticalScrollBarPolicy(VERTICAL_SCROLLBAR_NEVER);

				}
				buttonPanel.setEnabled(false);
				if(agregarloteButton!=null) {
					agregarloteButton.setEnabled(false);
				}
				if(modificarloteButton!=null) {
					modificarloteButton.setEnabled(false);
				}
				if(eliminarloteButton!=null) {
					eliminarloteButton.setEnabled(false);
				}
				if(verificarPlanButton!=null) {
					verificarPlanButton.setEnabled(false);
				}

				databaseButton.setText("Cambiar Dia");
				databaseButton.setIcon(deshacer);
				databaseButton.setActionCommand(Constants.DESHACER_PLAN);
				databaseButton.setEnabled(true);
				//this.revalidate();
				//this.repaint();
			}

			cards.remove(3);
		}
		else {

			buttonPanel = new JPanel();
			buttonPanel.setLayout(new BorderLayout());


			JPanel imagePanel = new JPanel(new BorderLayout());
			imagePanel.add(imagelabel, BorderLayout.EAST);


			gridPanel = new JPanel(new BorderLayout());

			JPanel errorPanel = new JPanel(new BorderLayout());

			String labelText = message;
			JLabel textLabel = new JLabel(labelText, JLabel.CENTER);

			errorPanel.add(textLabel,BorderLayout.CENTER);
			errorPanel.add(buttonPanel,BorderLayout.SOUTH);

			gridPanel.add(errorPanel, BorderLayout.CENTER);
			gridPanel.add(imagePanel, BorderLayout.SOUTH);

		}
		cards.add(gridPanel, Constants.PlanLabel.GRID_PANEL.toString());
	}

	public void actionPerformed(ActionEvent e) {

		String command = e.getActionCommand();

		String array[] = ((String) monthsCombo.getSelectedItem()).split("/");

		listOfMensuales = db.retrieveMensuales(
				array[0], array[1], array[2]);

		dayselected = daysCombo.getSelectedIndex();

		day = new DateTime(Integer.valueOf(array[2]), Constants.monthsmap.get(array[1]), Integer.valueOf(array[0]), 0, 0);

		int currentDia = Integer.valueOf(array[0])+Integer.valueOf(dayselected);
		//int actualizarDia = db.actionToPerform(Integer.valueOf(array[0]), currentDia , array[1], array[2], "actualizar");

		////System.out.println("command=" + command);
		if (command == Constants.PLAN_MOSTRAR) {

			((GercoPlaneacion) parent).setMonthSelection(monthsCombo.getSelectedIndex());
			((GercoPlaneacion) parent).setYearSelection(yearCombo.getSelectedIndex());
			((GercoPlaneacion) parent).setDaySelection(daysCombo.getSelectedIndex());
			
			if(mostrarButton!=null) {
				mostrarButton.setEnabled(true);
			}
			if(monthsCombo!=null) {
				monthsCombo.setEnabled(true);
			}
			if(yearCombo!=null) {
				yearCombo.setEnabled(true);
			}
			if(daysCombo!=null) {
				daysCombo.setEnabled(true);
			}

			this.repaint();
			CardLayout cl = (CardLayout) (cards.getLayout());
			if (listOfMensuales.size() > 0) {



				/********************
				 * 
				 * se muestra el plan si este ya existe en la base de datos
				 * o se da la opcion de crearlo si no existe
				 * 
				 */


				month = array[1];
				year = array[2];

				// this.removeAll();
				createPlan(array[0], array[1], array[2], false);

				daysCombo.setSelectedIndex(0);
				daysCombo.setEnabled(true);

				//jsp.setHorizontalScrollBarPolicy(counter);

				cl.show(cards, Constants.PlanLabel.GRID_PANEL.toString());
			} else {
				daysCombo.setEnabled(false);
				cl.show(cards, Constants.PlanLabel.PANEL_ERROR_LISTA_NO_CREADA.toString());
			}

		}  else if ("comboBoxChanged".equals(command)) {
			////System.out.println("User has selected an item from the combo box.");

			daysCombo.setEnabled(false);
			glassPanel.setVisible(true);

			if(tablescrollpane!=null) {
				tablescrollpane.setHorizontalScrollBarPolicy(HORIZONTAL_SCROLLBAR_NEVER);
				tablescrollpane.setVerticalScrollBarPolicy(VERTICAL_SCROLLBAR_NEVER);

			}
			buttonPanel.setEnabled(false);
			if(agregarloteButton!=null) {
				agregarloteButton.setEnabled(false);
			}
			if(modificarloteButton!=null) {
				modificarloteButton.setEnabled(false);
			}
			if(eliminarloteButton!=null) {
				eliminarloteButton.setEnabled(false);
			}
			if(verificarPlanButton!=null) {
				verificarPlanButton.setEnabled(false);
			}
			if(databaseButton!=null) {
				databaseButton.setEnabled(false);
			}

			monthsCombo = new JComboBox(Constants.getStartWeek(String
					.valueOf((Integer.valueOf((String) yearCombo
							.getSelectedItem())))));
			monthsCombo.setActionCommand("monthsComboChanged");
			monthsCombo.addActionListener(this);
			JPanel topPanel = new JPanel(new BorderLayout());

			// yearCombo = new
			// JComboBox(Constants.singleArrayListToString(years));
			// monthsCombo = new JComboBox(months);
			// daysCombo = new JComboBox(Constants.singleArrayListToString(days
			// .get(currentMonth)));

			JPanel leftPanel = new JPanel(new BorderLayout());
			JPanel datePanel = new JPanel(new BorderLayout());
			JPanel mostrarPanel = new JPanel(new BorderLayout());

			leftPanel.add(datePanel, BorderLayout.CENTER);
			leftPanel.add(mostrarPanel, BorderLayout.EAST);

			topPanel.add(leftPanel, BorderLayout.EAST);

			datePanel.add(daysCombo, BorderLayout.WEST);
			datePanel.add(monthsCombo, BorderLayout.CENTER);
			datePanel.add(yearCombo, BorderLayout.EAST);

			leftPanel.add(mostrarButton, BorderLayout.EAST);
			// topPanel

			this.removeAll();

			this.setLayout(new BorderLayout());
			this.add(topPanel, BorderLayout.NORTH);
			this.add(cards, BorderLayout.CENTER);
			// this.add(buttonPanel, BorderLayout.SOUTH);

			this.revalidate();
			this.repaint();
			this.setVisible(true);
		}
		else if("daysComboChanged".equals(command)) {

			//	//System.out.println("entro a days combo");

			CardLayout cl = (CardLayout) (cards.getLayout());

			month = array[1];
			year = array[2];

			dayselected = daysCombo.getSelectedIndex();

			plan.printTable(dayselected+1);

			// this.removeAll();
			createPlan(array[0], array[1], array[2], true);

			cl.show(cards, Constants.PlanLabel.GRID_PANEL.toString());
		}
		else if("monthsComboChanged".equals(command)) {
			//gridFrame.setEnabled(false);
			//mt.setEnabled(false);
			if(tablescrollpane!=null) {
				tablescrollpane.setHorizontalScrollBarPolicy(HORIZONTAL_SCROLLBAR_NEVER);
				tablescrollpane.setVerticalScrollBarPolicy(VERTICAL_SCROLLBAR_NEVER);
			}

			if(agregarloteButton!=null) {
				agregarloteButton.setEnabled(false);
			}
			if(modificarloteButton!=null) {
				modificarloteButton.setEnabled(false);
			}
			if(eliminarloteButton!=null) {
				eliminarloteButton.setEnabled(false);
			}
			if(verificarPlanButton!=null) {
				verificarPlanButton.setEnabled(false);
			}
			if(databaseButton!=null) {
				databaseButton.setEnabled(false);
			}

			buttonPanel.setEnabled(false);
			glassPanel.setVisible(true);
			daysCombo.setEnabled(false);

		}
		else if(Constants.MODIFICAR_LOTE.equals(command)) {
			month = array[1];
			year = array[2];

			int dayselected = daysCombo.getSelectedIndex();

			@SuppressWarnings("unused")
			//TODO change modificar lote days
			ModificarLote ventana = new ModificarLote(Constants
					.getParentFrame(this),this,day.plusDays(dayselected).getDayOfWeek());

			if(ventana.getStatus()) {
				databaseButton.setEnabled(false);
			}
			else {

			}
		}
		else if(Constants.AGREGAR_LOTE.equals(command)) {

			listOfMensuales = db.retrieveListMensuales(String.valueOf(plan.planday),
					plan.month, plan.year);

			int unidades = 0;
			for(int i=0;i<listOfMensuales.size();i++) {
				unidades += Integer.valueOf(listOfMensuales.get(i).get(4))
						- plan.getUnidadesComprometidas(listOfMensuales.get(i).get(0));
			}


			if(unidades>0) {

				month = array[1];
				year = array[2];

				int dayselected = daysCombo.getSelectedIndex();

				@SuppressWarnings("unused")
				//TODO 
				AgregarLote ventana = new AgregarLote(Constants
						.getParentFrame(this),this,day.getDayOfMonth()+dayselected);

				if(ventana.getStatus()) {
					databaseButton.setEnabled(false);
				}
				else {
					// do nothing
				}
			}
			else {
				JOptionPane
				.showMessageDialog(
						new JFrame(),
						"No es posible crear mas lotes: todos los productos \n"+ 
								"semanales ya se encuentran distribuidos en lotes",
								"Mensaje de Error",
								JOptionPane.ERROR_MESSAGE);
			}

		}
		else if(Constants.ELIMINAR_LOTE.equals(command)) {

			month = array[1];
			year = array[2];

			int dayselected = daysCombo.getSelectedIndex();

			int loteindex = Integer.valueOf(selectedradio);

			boolean removecheck = plan.lotes.get(loteindex).esPosibleBorrarLote(day.plusDays(dayselected).getDayOfWeek());

			if(removecheck) {
				if(plan.removeLote(loteindex)!=0) {

					CardLayout cl = (CardLayout) (cards.getLayout());
					plan.printTable(dayselected+1);
					createPlan(array[0], array[1], array[2], true);
					databaseButton.setEnabled(false);
					cl.show(cards, Constants.PlanLabel.GRID_PANEL.toString());
				}
				else {
					JOptionPane
					.showMessageDialog(
							new JFrame(),
							"Debe existir al menos un lote",
							"Mensaje de Error",
							JOptionPane.ERROR_MESSAGE);
				}
			}
			else {
					JOptionPane
					.showMessageDialog(
							new JFrame(),
							"Lote contiene informacion que ya ha sido\nconfirmada en dias anteriores",
							"Mensaje de Error",
							JOptionPane.ERROR_MESSAGE);
			}



		}
		else if(Constants.VERIFICAR_PLAN.equals(command)) {
			month = array[1];
			year = array[2];
			int dayselected = daysCombo.getSelectedIndex();

			setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
			task = new Task(day.plusDays(dayselected).getDayOfMonth(),dayselected,month,year,"verificar");
			task.addPropertyChangeListener(this);
			task.execute();
			progdialog = new ProgressMonitor(Constants.getParentFrame(this));
			progdialog
			.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
			progdialog
			.setLocationRelativeTo(Constants.getParentFrame(this));
			progdialog.pack();
			progdialog.setVisible(true);

			if(task.valid == true) {
				JOptionPane
				.showMessageDialog(
						new JFrame(),
						"Plan no tiene conflictos",
						"Verificacion Terminada",
						JOptionPane.INFORMATION_MESSAGE);

				databaseButton.setEnabled(true);
			}
			else {
				JOptionPane
				.showMessageDialog(
						new JFrame(),
						task.getError(),
						"Verificacion Terminada",
						JOptionPane.ERROR_MESSAGE);
			}
		}
		else if (command == Constants.CONFIRMAR_PLAN) {
			Object[] options = {"SI",
			"No"};
			int response = JOptionPane
					.showOptionDialog(
							new JFrame(),
							"Esta seguro de que desea agregar la\n" +
									"informacion de la produccion real?",
									"Confirmacion agregar informacion del dia",
									JOptionPane.YES_NO_CANCEL_OPTION,
									JOptionPane.QUESTION_MESSAGE,
									database,
									options,
									options[0]);
			if(response == 0) {
				//daysCombo.setEnabled(false);


				//confirm.insertActionToPerform(day+dayselected, month, year, "actualizar");

				//DateTime day = new DateTime(Integer.valueOf(year), Constants.monthsmap.get(month), day2, 0, 0) ;

				month = array[1];
				year = array[2];
				int dayselected = daysCombo.getSelectedIndex();



				//db.retrieveMensuales(

				setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));



				task = new Task(day.getDayOfMonth(),dayselected,month,year,"confirmar");
				task.addPropertyChangeListener(this);
				task.execute();
				progdialog = new ProgressMonitor(Constants.getParentFrame(this));
				progdialog
				.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
				progdialog
				.setLocationRelativeTo(Constants.getParentFrame(this));
				progdialog.pack();
				progdialog.setVisible(true);


				int actualizarplanday = dayselected + 1;
				
				if(actualizarplanday < 6) {
					JOptionPane
					.showMessageDialog(
							new JFrame(),
							"Se procedera a actualizar el plan para\nlos dias restantes de la semana",
							"Confirmacion Terminada",
							JOptionPane.INFORMATION_MESSAGE);
	
					
	
	
					setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
	
					task = new Task(day.getDayOfMonth(),actualizarplanday,month,year,"actualizar");
					task.addPropertyChangeListener(this);
					task.execute();
					progdialog = new ProgressMonitor(Constants.getParentFrame(this));
					progdialog
					.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
					progdialog
					.setLocationRelativeTo(Constants.getParentFrame(this));
					progdialog.pack();
					progdialog.setVisible(true);
	
					JOptionPane
					.showMessageDialog(
							new JFrame(),
							"Actualizacion de plan terminada",
							"Actualizacion Terminada",
							JOptionPane.INFORMATION_MESSAGE);
				}
				else {
					
					DateTime nextweekday = day.plusDays(7);
					
					ArrayList<ArrayList<String>> listOfMensuales = db.retrieveMensuales(
							String.valueOf(nextweekday.getDayOfMonth()),
							String.valueOf(Constants.months[nextweekday.getMonthOfYear()-1]),
							String.valueOf(nextweekday.getYear()));
					
					int nextweekconfirmados = db.countWeekConfirmados(nextweekday.getDayOfMonth(),
							String.valueOf(Constants.months[nextweekday.getMonthOfYear()-1]),
							String.valueOf(nextweekday.getYear()));
					
					if(listOfMensuales.size() > 0 && nextweekconfirmados == 0) {
						JOptionPane
						.showMessageDialog(
								new JFrame(),
								"Se procedera a actualizar la siguiente semana",
								"Confirmacion Terminada",
								JOptionPane.INFORMATION_MESSAGE);
		
						
		
		
						setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
		
						task = new Task(
								nextweekday.getDayOfMonth(),
								0,
								String.valueOf(Constants.months[nextweekday.getMonthOfYear()-1]),
								String.valueOf(nextweekday.getYear()),
								"actualizar");
						
						task.addPropertyChangeListener(this);
						task.execute();
						progdialog = new ProgressMonitor(Constants.getParentFrame(this));
						progdialog
						.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
						progdialog
						.setLocationRelativeTo(Constants.getParentFrame(this));
						progdialog.pack();
						progdialog.setVisible(true);
		
						JOptionPane
						.showMessageDialog(
								new JFrame(),
								"Actualizacion de plan terminada",
								"Actualizacion Terminada",
								JOptionPane.INFORMATION_MESSAGE);
					}
					else if(listOfMensuales.size() == 0){
						JOptionPane
						.showMessageDialog(
								new JFrame(),
								"No se actualizara plan porque no se ha creado\nplan de produccion de siguiente semana",
								"Confirmacion Terminada",
								JOptionPane.INFORMATION_MESSAGE);
					}
					else if(nextweekconfirmados != 0){
						JOptionPane
						.showMessageDialog(
								new JFrame(),
								"No se actualizara plan porque existen dias \nconfirmados en siguiente semana",
								"Confirmacion Terminada",
								JOptionPane.INFORMATION_MESSAGE);
					}
				}

				// this.removeAll();

				/*while (tempPlan.done == false) {
					try {
						// pbar.
						Thread.sleep(10);
						// task.firePropertyChange(day, month, year);
					} catch (InterruptedException exc) {
						exc.printStackTrace();
					}
				}*/

				//daysCombo.setSelectedIndex(0);
				daysCombo.setEnabled(true);

				//jsp.setHorizontalScrollBarPolicy(counter);

				//changestatus = true;
				glassPanel.setVisible(true);

				if(tablescrollpane!=null) {
					tablescrollpane.setHorizontalScrollBarPolicy(HORIZONTAL_SCROLLBAR_NEVER);
					tablescrollpane.setVerticalScrollBarPolicy(VERTICAL_SCROLLBAR_NEVER);

				}
				buttonPanel.setEnabled(false);
				if(agregarloteButton!=null) {
					agregarloteButton.setEnabled(false);
				}
				if(modificarloteButton!=null) {
					modificarloteButton.setEnabled(false);
				}
				if(eliminarloteButton!=null) {
					eliminarloteButton.setEnabled(false);
				}
				if(verificarPlanButton!=null) {
					verificarPlanButton.setEnabled(false);
				}

				databaseButton.setText("Cambiar Dia");
				databaseButton.setIcon(deshacer);
				databaseButton.setActionCommand(Constants.DESHACER_PLAN);

				/*for(int i =0 ; i< radiobuttons.size(); i++) {
					radiobuttons.get(i).setEnabled(false);
					radiobuttons.get(i).setFocusable(false);
				}*/
				changestatus = true;
				//this.updateStatusAfterConfirmar();
				this.revalidate();
				this.repaint();
			}

		}
		else if (command == Constants.DESHACER_PLAN) {
			Object[] options = {"SI",
			"No"};
			int response = JOptionPane
					.showOptionDialog(
							new JFrame(),
							"Esta seguro de que desea cambiar la\n" +
									"informacion de la produccion real?",
									"Confirmacion cambiar informacion del dia",
									JOptionPane.YES_NO_CANCEL_OPTION,
									JOptionPane.QUESTION_MESSAGE,
									database,
									options,
									options[0]);
			if(response == 0) {
				Database confirm = new Database();

				confirm.changeStatusOfLote(day.getDayOfMonth(),1,day.plusDays(dayselected).getDayOfWeek(), month, year,false);
				confirm.deleteDiaConfirmado(day.plusDays(dayselected).getDayOfWeek(),day.getDayOfMonth(), month, year);

				//databaseButton.setEnabled(false);
				glassPanel.setVisible(false);

				if(tablescrollpane!=null) {
					tablescrollpane.setHorizontalScrollBarPolicy(HORIZONTAL_SCROLLBAR_AS_NEEDED );
					tablescrollpane.setVerticalScrollBarPolicy(VERTICAL_SCROLLBAR_AS_NEEDED);
				}
				buttonPanel.setEnabled(true);

				if(agregarloteButton!=null) {
					agregarloteButton.setEnabled(true);
				}
				if(modificarloteButton!=null) {
					modificarloteButton.setEnabled(true);
				}
				if(eliminarloteButton!=null) {
					eliminarloteButton.setEnabled(true);
				}
				if(verificarPlanButton!=null) {
					verificarPlanButton.setEnabled(true);
				}



				databaseButton.setText("Confirmar Dia");
				databaseButton.setIcon(planicon);
				databaseButton.setActionCommand(Constants.CONFIRMAR_PLAN);
				databaseButton.setEnabled(false);
				for(int i =0 ; i< radiobuttons.size(); i++) {
					radiobuttons.get(i).setEnabled(true);
					radiobuttons.get(i).setFocusable(true);
				}
				radioPanel.setEnabled(true);
				changestatus = true;
				this.revalidate();
				this.repaint();
			}
		}
		else if(command.equals(Constants.SET_LOTE_INDEX)){
			JRadioButton button = (JRadioButton) e.getSource();
			selectedradio = button.getName();
		}

	}

	public void propertyChange(PropertyChangeEvent evt) {
		if ("progress" == evt.getPropertyName()) {
			int progress = (Integer) evt.getNewValue();
			pbar.setValue(progress);
		}
	}

	public class ConfirmarDia extends Thread {

		DateTime day;
		int dayselected;
		String month;
		String year;
		int confirmarcount;
		Planner plan;


		public ConfirmarDia(DateTime day, int dayselected, String month, String year, Planner plan) {
			super();
			this.plan = plan;/*new Planner(plan);*/
			this.day = day;
			this.dayselected = dayselected;
			this.month = month;
			this.year = year;
			confirmarcount = 0;
		}


		public synchronized void run() {

			Database confirm = new Database();



			db.deleteAllLotesFromWeek(day.getDayOfMonth(),month,year);

			for (int i = 0; i < plan.loteids.size(); i++) {
				confirmarcount ++;
				int index = plan.loteids.get(i);

				int fases[] = plan.lotes.get(index).getFases(day.plusDays(dayselected).getDayOfWeek());

				int sum = 0;
				for(int j=0;j<fases.length;j++) {
					if(fases[j] != -1)
						sum++;
				}

					//System.out.println("index=" + index);
				
				if(plan.lotes.get(index).loteday == day.plusDays(dayselected).getDayOfWeek()) {
					plan.lotes.get(index).confirmLoteReal(0);
					for (int j=0; j < fases.length; j++) {
						if(fases[j]!=-1) {
							plan.lotes.get(index).confirmDaySlotReal(j+1,false,day.plusDays(dayselected).getDayOfWeek(),day.plusDays(dayselected).getDayOfWeek());
						}
							confirmarcount++;
					}
				}
				else if(sum != 0 && plan.lotes.get(index).loteday > day.plusDays(dayselected).getDayOfWeek() ) {
					plan.lotes.get(index).modifyPlanDayLote(day.plusDays(dayselected).getDayOfWeek());
					plan.lotes.get(index).changeLoteDay(day.plusDays(dayselected).getDayOfWeek());
					for (int j=0; j < fases.length; j++) {
						if(fases[j]!=-1) {
							plan.lotes.get(index).confirmDaySlotReal(j+1,false,day.plusDays(dayselected).getDayOfWeek(),day.plusDays(dayselected).getDayOfWeek());
						}
							confirmarcount++;
					}
				}
				else if(plan.lotes.get(index).loteday < day.plusDays(dayselected).getDayOfWeek() ) {
					//System.out.println(" en conditional 3");
					for (int j=0; j < fases.length; j++) {
						if(fases[j]!=-1) {
							plan.lotes.get(index).confirmDaySlotReal(j+1,false,day.plusDays(dayselected).getDayOfWeek(),day.plusDays(dayselected).getDayOfWeek());
						}
							confirmarcount++;
					}
				}

				/*for (int j=0; j < fases.length; j++) {
					//if(fases[j]!=-1) {
						plan.lotes.get(index).confirmDaySlotReal(j+1,false,day.plusDays(dayselected).getDayOfWeek(),plan.planday.plusDays(5).getDayOfWeek());
						//}
						confirmarcount++;
				}*/
			}

			confirm.changeStatusOfLote(day.getDayOfMonth(),day.getDayOfWeek(),day.plusDays(dayselected).getDayOfWeek(), month, year,true);
			confirm.insertDiaConfirmado(day.plusDays(dayselected).getDayOfWeek(),day.getDayOfMonth(), month, year);
			confirm.closeConnection();
			confirmarcount = 110;
		}

		public int getConfirmarCount() {
			return confirmarcount;
		}
	}
	@SuppressWarnings("serial")
	public class AgregarLote extends JDialog implements ActionListener, ListSelectionListener {

		JPanel addlotepanel;
		int day;
		JFrame parentframe;
		PanelConfirmar parentpanel;
		Container contentPane;
		//ArrayList<ArrayList<String>> listOfMensuales;
		JTextField programadas,pendientes,unidadesnuevolote,producto;
		String produccionid;
		int unidades;
		String productid;
		String productname;
		IndexedList mensualeslist,maquina;
		HashMap<String,ArrayList<String>> maquinasProduccion;
		int unidadenml, necesidadenlitros, capacidadmaquinaasignada;
		ArrayList<String>  maquinariaseleccionada;
		boolean agregado;



		public AgregarLote(JFrame parent,PanelConfirmar parentpanel,int day) {
			super(parent, "Agregar Lote",
					Dialog.ModalityType.DOCUMENT_MODAL);
			this.day = day;
			this.parentframe = parent;
			this.parentpanel = parentpanel;
			agregado = false;

			contentPane = getContentPane();
			//contentPane.setSize(150,700);

			/*listOfMensuales = db.retrieveListMensuales(String.valueOf(plan.planday),
					plan.month, plan.year);*/

			JPanel addlotepanel = new JPanel();
			addlotepanel.setLayout(new GridBagLayout());



			Border loweredbevel = BorderFactory.createLoweredBevelBorder();

			Border border = BorderFactory.createTitledBorder(loweredbevel,
					"Seleccione produccion mensual");

			Border grayborder = BorderFactory
					.createLineBorder(Color.LIGHT_GRAY);

			addlotepanel.setBorder(border);


			String[] nameOfMensuales = new String[listOfMensuales.size()];
			ArrayList<String> idOfMensuales = new ArrayList<String>();

			for(int i=0;i<listOfMensuales.size();i++) {
				nameOfMensuales[i] = "(" + listOfMensuales.get(i).get(2) + ") unidades:" + listOfMensuales.get(i).get(4);
				idOfMensuales.add(listOfMensuales.get(i).get(0));
			}


			mensualeslist = new IndexedList(new DefaultListModel(),nameOfMensuales,idOfMensuales,0);

			mensualeslist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
			mensualeslist.setSelectedIndex(0);

			unidadenml = Integer.valueOf(listOfMensuales.get(0).get(3));
			produccionid = listOfMensuales.get(0).get(0);
			unidades = 0;
			productid = listOfMensuales.get(0).get(1);
			productname = listOfMensuales.get(0).get(2);

			mensualeslist.setFixedCellWidth(300);
			mensualeslist.setVisibleRowCount(5);

			mensualeslist.addListSelectionListener(this);

			JScrollPane scrollpane = new JScrollPane(mensualeslist);
			JPanel mensualespane = new JPanel(new BorderLayout());
			mensualespane.add(scrollpane,BorderLayout.NORTH);

			GridBagConstraints c = new GridBagConstraints();

			c.weightx = 1;
			c.anchor = GridBagConstraints.WEST;
			//c.gridwidth = 1;
			//c.fill = GridBagConstraints.HORIZONTAL;
			//c.gridy = 3;
			c.gridy = 0;

			mensualespane.setBorder(grayborder);

			addlotepanel.add(mensualespane,c);



			JPanel unidadespane = new JPanel();
			unidadespane.setLayout(new BoxLayout(unidadespane, BoxLayout.X_AXIS));

			JPanel labelpane = new JPanel();
			labelpane.setLayout(new GridLayout(2,1));

			JPanel textpane = new JPanel();
			textpane.setLayout(new GridLayout(2,1));

			JLabel unidadesprogramadas = new JLabel("Programadas");

			programadas = new JTextField();
			programadas.setText(String.valueOf(plan.getUnidadesComprometidas(mensualeslist.getValue())));
			programadas.setColumns(programadas.getText().length()+2);
			programadas.setEditable(false);
			programadas.setFocusable(false);
			//programadas.setEnabled(false);

			JLabel unidadespendientes = new JLabel("Pendientes");

			pendientes = new JTextField();
			pendientes.setText(String.valueOf(Integer.valueOf(listOfMensuales.get(mensualeslist.getSelectedIndex()).get(4)) - 
					plan.getUnidadesComprometidas(mensualeslist.getValue())));
			pendientes.setColumns(pendientes.getText().length()+2);
			pendientes.setEditable(false);
			pendientes.setFocusable(false);
			//pendientes.setEnabled(false);

			labelpane.add(unidadesprogramadas);
			labelpane.add(unidadespendientes);

			textpane.add(programadas);
			textpane.add(pendientes);

			unidadespane.add(labelpane, BorderLayout.WEST);
			unidadespane.add(Box.createRigidArea(new Dimension(10, 25)));
			unidadespane.add(textpane, BorderLayout.CENTER);


			c = new GridBagConstraints();

			c.weightx = 1;
			c.weighty = 1;
			//c.anchor = GridBagConstraints.WEST;
			c.fill = GridBagConstraints.HORIZONTAL;
			//c.gridy = 3;
			c.gridy = 2;

			unidadespane.setBorder(grayborder);

			addlotepanel.add(unidadespane,c);

			contentPane.add(addlotepanel,BorderLayout.NORTH);

			border = BorderFactory.createTitledBorder(loweredbevel,
					"Informacion Lote Nuevo");

			JPanel loteinfopanel = new JPanel();
			loteinfopanel.setLayout(new GridBagLayout());

			loteinfopanel.setBorder(border);

			JPanel infopane = new JPanel();
			infopane.setLayout(new BoxLayout(infopane, BoxLayout.X_AXIS));

			labelpane = new JPanel();
			labelpane.setLayout(new GridBagLayout());

			textpane = new JPanel();
			textpane.setLayout(new GridBagLayout());

			JLabel productolabel = new JLabel("Producto");

			producto = new JTextField();
			producto.setText(listOfMensuales.get(mensualeslist.getSelectedIndex()).get(2));
			producto.setColumns(producto.getText().length()+2);
			producto.setEditable(false);
			producto.setFocusable(false);


			ArrayList<String> maquinariaProduccionIds = db.retrieveMaquinariaByFase(Integer.valueOf(listOfMensuales.get(mensualeslist.getSelectedIndex()).get(1)), 3);
			maquinasProduccion = db.retrieveMapMaquinaria(0);
			String[] maquinaProduccionNames = new String[maquinariaProduccionIds.size()];

			for(int i=0;i<maquinariaProduccionIds.size();i++) {
				maquinaProduccionNames[i] = maquinasProduccion.get(maquinariaProduccionIds.get(i)).get(1);
			}

			JLabel maquinalabel = new JLabel("Tanque");

			maquina = new IndexedList(new DefaultListModel(),maquinaProduccionNames,maquinariaProduccionIds,1);


			maquina.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
			maquina.setSelectedIndex(0);
			maquina.setFixedCellWidth(100);
			maquina.setVisibleRowCount(3);
			maquina.addListSelectionListener(this);

			maquinariaseleccionada = maquinasProduccion.get(maquina.getValue());
			capacidadmaquinaasignada = Integer
					.valueOf(maquinariaseleccionada.get(5));

			JScrollPane maquinascrollpane = new JScrollPane(maquina);

			producto.setText(listOfMensuales.get(mensualeslist.getSelectedIndex()).get(2));
			producto.setColumns(producto.getText().length()+2);
			producto.setEditable(false);
			producto.setFocusable(false);

			JLabel uninuevolotelabel = new JLabel("Unidades");

			unidadesnuevolote = new JTextField();
			unidadesnuevolote.setText("0");
			unidadesnuevolote.setColumns(15);

			c = new GridBagConstraints();
			c.weighty = 0.25;
			c.anchor = GridBagConstraints.WEST;
			c.gridx = 0;
			c.gridy = 0;

			labelpane.add(productolabel,c);

			c = new GridBagConstraints();

			c.weighty = 0.25;
			c.anchor = GridBagConstraints.WEST;
			c.gridx = 0;
			c.gridy = 1;
			c.gridheight = 3;

			labelpane.add(maquinalabel, c);

			c = new GridBagConstraints();
			c.weighty = 0.25;
			c.anchor = GridBagConstraints.WEST;
			c.gridx = 0;
			c.gridy = 4;

			labelpane.add(uninuevolotelabel,c);

			c = new GridBagConstraints();
			c.gridx = 0;
			c.anchor = GridBagConstraints.WEST;
			c.gridy = 0;

			textpane.add(producto,c);

			c = new GridBagConstraints();
			c.gridx = 0;
			c.anchor = GridBagConstraints.WEST;
			c.gridy = 1;
			c.gridheight = 3;

			textpane.add(maquinascrollpane,c);

			c = new GridBagConstraints();
			c.gridx = 0;
			c.anchor = GridBagConstraints.WEST;
			c.gridy = 4;

			textpane.add(unidadesnuevolote,c);

			infopane.add(labelpane, BorderLayout.WEST);
			infopane.add(Box.createRigidArea(new Dimension(10, 25)));
			infopane.add(textpane, BorderLayout.CENTER);


			c = new GridBagConstraints();

			c.weightx = 1;
			c.weighty = 1;
			//c.anchor = GridBagConstraints.WEST;
			c.fill = GridBagConstraints.HORIZONTAL;
			//c.gridy = 3;
			c.gridy = 3;

			unidadespane.setBorder(grayborder);

			loteinfopanel.add(infopane,c);

			contentPane.add(loteinfopanel,BorderLayout.CENTER);

			JPanel confirmarbuttonpanel = new JPanel(new GridBagLayout());
			JButton cancelarbutton = new JButton("Cancelar",redicon);
			cancelarbutton.addActionListener(this);
			cancelarbutton.setActionCommand(Constants.CONFIRMAR_CANCELAR_AGREGAR_LOTE);

			c = new GridBagConstraints();

			c.insets = new Insets(15,0,15,0);
			c.weightx = 0.25;
			c.anchor = GridBagConstraints.CENTER;
			c.gridx = 0;
			c.gridy = 0;

			confirmarbuttonpanel.add(cancelarbutton, c);

			JButton confirmarbutton = new JButton("Confirmar",greenicon);
			confirmarbutton.addActionListener(this);
			confirmarbutton.setActionCommand(Constants.CONFIRMAR_AGREGAR_LOTE);

			c = new GridBagConstraints();

			c.insets = new Insets(15,0,15,0);
			c.weightx = 0.25;
			c.anchor = GridBagConstraints.CENTER;
			c.gridx = 1;
			c.gridy = 0;

			confirmarbuttonpanel.add(confirmarbutton, c);

			contentPane.add(confirmarbuttonpanel, BorderLayout.SOUTH);

			pack();

			setVisible(true);

		}

		@Override
		public void actionPerformed(ActionEvent e) {
			int necesidadenlitros = 0;
			String command = e.getActionCommand();

			String array[] = ((String) monthsCombo.getSelectedItem()).split("/");

			if (command == Constants.CONFIRMAR_AGREGAR_LOTE) {

				boolean validunidades = true;
				boolean topeunidades = true;

				try {
					Integer.parseInt(unidadesnuevolote.getText());
					unidades = Integer.valueOf(unidadesnuevolote.getText());
					necesidadenlitros = (unidades * unidadenml) / 1000;
					////System.out.println("necesidad en litros " + necesidadenlitros);
					////System.out.println("capacidadmaquinaasignada " + capacidadmaquinaasignada);
					if(necesidadenlitros>capacidadmaquinaasignada) {
						topeunidades = false;
					}

				} catch (Exception exp) {
					validunidades = false;
				}


				if(validunidades) {

					if(topeunidades) {
						if(Integer.valueOf(unidadesnuevolote.getText()) < 1) {
							JOptionPane
							.showMessageDialog(
									new JFrame(),
									"Seleccione cantidad de unidades valida",
									"Mensaje de Error",
									JOptionPane.ERROR_MESSAGE);
						}
						else if(Integer.valueOf(unidadesnuevolote.getText())>Integer.valueOf(pendientes.getText())) {
							unidadesnuevolote.setText("0");
							JOptionPane
							.showMessageDialog(
									new JFrame(),
									"unidades de lote no pueden sobrepasar las \n" +
											"unidades pendientes por programar",
											"Mensaje de Error",
											JOptionPane.ERROR_MESSAGE);
						}
						else {

							int nextloteid = plan.getNextLoteID();

							plan.addLote(nextloteid,0,day,produccionid, necesidadenlitros, unidades,
									productid, productname, false, 0,1);
							//TODO check for startingfase of lote added

							plan.increaseNextLoteID();

							plan.lotes.get(nextloteid).setupFakeDispensacionSlot(maquinariaseleccionada.get(0),maquinariaseleccionada.get(1));
							plan.lotes.get(nextloteid).setupFakeProduccionSlot(maquinariaseleccionada.get(0),maquinariaseleccionada.get(1));
							plan.lotes.get(nextloteid).clearSlots(day, 1, 0);
							plan.lotes.get(nextloteid).clearSlots(day, 2, 0);

							CardLayout cl = (CardLayout) (cards.getLayout());
							plan.printTable(day);
							parentpanel.createPlan(array[0], array[1], array[2], true);
							cl.show(cards, Constants.PlanLabel.GRID_PANEL.toString());
							agregado = true;
							this.dispose();

						}
					}
					else {
						JOptionPane
						.showMessageDialog(
								new JFrame(),
								"unidades asignadas sobrepasan capacidad de tanque\n" +
										"(unidades asignadas equivalen a " + necesidadenlitros + " litros)", 
										"Mensaje de Error",
										JOptionPane.ERROR_MESSAGE);
					}
				}
				else {
					JOptionPane
					.showMessageDialog(
							new JFrame(),
							"Ingrese un numero en campo de unidades",
							"Mensaje de Error",
							JOptionPane.ERROR_MESSAGE);

				}

			} else if (command == Constants.CONFIRMAR_CANCELAR_AGREGAR_LOTE) {

				dispose();
			}
		}

		@Override
		public void valueChanged(ListSelectionEvent e) {

			IndexedList source = (IndexedList) e.getSource();

			if(source.getIndex() == 0) {

				int comprometidas = plan.getUnidadesComprometidas(source.getValue());
				programadas.setText(String.valueOf(comprometidas));
				pendientes.setText(String.valueOf(Integer.valueOf(listOfMensuales.get(source.getSelectedIndex()).get(4)) - 
						comprometidas));
				producto.setText(listOfMensuales.get(source.getSelectedIndex()).get(2));

				produccionid = listOfMensuales.get(source.getSelectedIndex()).get(0);
				productid = listOfMensuales.get(source.getSelectedIndex()).get(1);
				productname = listOfMensuales.get(source.getSelectedIndex()).get(2);
				unidadenml = Integer.valueOf(listOfMensuales.get(mensualeslist.getSelectedIndex()).get(3));
			}
			else if(source.getIndex() == 1) {


				maquinariaseleccionada = maquinasProduccion.get(source.getValue());
				capacidadmaquinaasignada = Integer
						.valueOf(maquinariaseleccionada.get(5));


			}
		}

		public boolean getStatus() {
			return agregado;
		}

	}


	public class ModificarLote extends JDialog implements ActionListener, ListSelectionListener {

		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;
		Container contentPane;
		JPanel modlotepanel;
		JPanel modlotefasespanel;
		int maquinalistindex;
		int funcionariolistindex;
		ArrayList<String> maquinariaProduccionIds;
		ArrayList<String> maquinariaLlenadoIds;
		ArrayList<String> maquinariaLoteadoIds;
		ArrayList<String> allFuncionarioNames;
		ArrayList<String> allFuncionarioIds;
		HashMap<String,ArrayList<String>> funcionarioProduccionNames;
		HashMap<String,ArrayList<String>> funcionarioLlenadoNames;
		HashMap<String,ArrayList<String>> funcionarioLoteadoNames;
		HashMap<String,ArrayList<String>> funcionarioProduccionIds;
		HashMap<String,ArrayList<String>> funcionarioLlenadoIds;
		HashMap<String,ArrayList<String>> funcionarioLoteadoIds;
		int day;
		ArrayList<ArrayList<JPanel>> fasepanel;
		ArrayList<ArrayList<JComboBox>> iniciotime;
		ArrayList<ArrayList<JComboBox>> fintime;
		ArrayList<ArrayList<JCheckBox>> finalizado;
		ArrayList<ArrayList<JTextField>> unidades;
		ArrayList<ArrayList<Integer>> unidadesanteriores;
		ArrayList<ArrayList<IndexedList>> funcionariosList;
		ArrayList<ArrayList<IndexedList>> maquinasList;
		ArrayList<JScrollPane> funcionariospane;
		Border loweredbevel,border,grayborder;
		JPanel iniciopanel, finpanel;
		JLabel iniciolabel, finlabel;
		boolean loteado, etiquetado, bandas;
		int loteindex;
		JFrame parentframe;
		PanelConfirmar parentpanel;
		ArrayList<Integer> fasesindex;
		int fasespanelindex;
		ArrayList<Integer> fasesagregarindex;
		int fasesagregarpanelindex;
		JButton borrarfase,agregarfase;
		JLabel defaultfase;
		JPanel defaultpanel;
		JScrollPane jsp;
		ArrayList<Integer> currentfases, toberemovedfases;
		boolean setup;
		final String[] fasenames;
		boolean modificado;
		Dimension scrnsize;
		int height;
		int width;

		public ModificarLote(JFrame parent,PanelConfirmar parentpanel,int day) {
			super(parent, "Modificar Lote",
					Dialog.ModalityType.DOCUMENT_MODAL);

			this.day = day;
			this.parentframe = parent;
			this.parentpanel = parentpanel;
			modificado = false;
			setup = false;

			Toolkit toolkit = Toolkit.getDefaultToolkit();
			scrnsize = toolkit.getScreenSize();

			String defaulttext = "<html><FONT COLOR=RED><B>Este Lote no tiene fases programadas para el dia </B></FONT>";
			defaultfase = new JLabel(defaulttext,JLabel.CENTER);

			defaultpanel = new JPanel(new BorderLayout());
			defaultpanel.add(defaultfase,BorderLayout.CENTER);
			defaultpanel.setEnabled(false);
			defaultpanel.setVisible(false);

			fasespanelindex = 0;
			fasesindex = new ArrayList<Integer>();

			fasesagregarpanelindex = 0;
			fasesagregarindex = new ArrayList<Integer>();

			currentfases = new ArrayList<Integer>();
			toberemovedfases = new ArrayList<Integer>();

			contentPane = getContentPane();
			//contentPane.setSize(150,700);

			modlotepanel = new JPanel();
			modlotepanel.setLayout(new BoxLayout(modlotepanel, BoxLayout.Y_AXIS));
			//modlotepanel.setMaximumSize(new Dimension(scrnsize.getSize().width-100,scrnsize.getSize().height-100));
			modlotepanel.add(defaultpanel);

			modlotefasespanel = new JPanel();

			jsp = new JScrollPane(modlotefasespanel,VERTICAL_SCROLLBAR_AS_NEEDED,HORIZONTAL_SCROLLBAR_NEVER);
			modlotepanel.add(jsp);


			funcionariospane = new ArrayList<JScrollPane>();
			loteindex = Integer.valueOf(selectedradio);


			int[] fases = plan.lotes.get(loteindex).getFases(day);

			fasenames = new String[]{"dispensacion","produccion","llenado","loteado","etiquetado","bandas","empaque"};

			String productid = plan.lotes.get(Integer.valueOf(selectedradio)).getproductID();
			int litros = plan.lotes.get(Integer.valueOf(selectedradio)).getLoteLitros();

			maquinariaProduccionIds = db.retrieveMaquinariaByFase(Integer.valueOf(productid), 3, litros);
			maquinariaLlenadoIds = db.retrieveMaquinariaByFase(Integer.valueOf(productid), 4);
			maquinariaLoteadoIds = db.retrieveMaquinariaByFase(Integer.valueOf(productid), 5);

			HashMap<String,ArrayList<String>> maquinasProduccion = db.retrieveMapMaquinaria(0);
			HashMap<String,ArrayList<String>> maquinasLlenado = db.retrieveMapMaquinaria(1);
			HashMap<String,ArrayList<String>> maquinasLoteado = db.retrieveMapMaquinaria(2);

			HashMap<String,ArrayList<String>> funcionarios = db.retrieveMapFuncionarios();

			String[] maquinaProduccionNames = new String[maquinariaProduccionIds.size()];

			funcionarioProduccionNames = new HashMap<String,ArrayList<String>>();
			funcionarioProduccionIds = new HashMap<String,ArrayList<String>>();

			for(int i=0;i<maquinariaProduccionIds.size();i++) {
				ArrayList<String> funcionarioIds = db
						.retrieveFuncionarioCapacidadOperar(Integer
								.valueOf(maquinariaProduccionIds.get(i)));

				ArrayList<String> names = new ArrayList<String>();

				for(int j=0;j<funcionarioIds.size();j++) {
					names.add(funcionarios.get(funcionarioIds.get(j)).get(2) + "," + funcionarios.get(funcionarioIds.get(j)).get(3));
				}

				funcionarioProduccionNames.put(maquinariaProduccionIds.get(i),names);
				funcionarioProduccionIds.put(maquinariaProduccionIds.get(i),funcionarioIds);

				maquinaProduccionNames[i] = maquinasProduccion.get(maquinariaProduccionIds.get(i)).get(1);
			}

			// setting up llenado maquinaria information

			String[] maquinaLlenadoNames = new String[maquinariaLlenadoIds.size()];

			funcionarioLlenadoNames = new HashMap<String,ArrayList<String>>();
			funcionarioLlenadoIds = new HashMap<String,ArrayList<String>>();

			for(int i=0;i<maquinariaLlenadoIds.size();i++) {
				ArrayList<String> funcionarioIds = db
						.retrieveFuncionarioCapacidadOperar(Integer
								.valueOf(maquinariaLlenadoIds.get(i)));

				ArrayList<String> names = new ArrayList<String>();

				for(int j=0;j<funcionarioIds.size();j++) {
					names.add(funcionarios.get(funcionarioIds.get(j)).get(2) + "," + funcionarios.get(funcionarioIds.get(j)).get(3));
				}

				funcionarioLlenadoNames.put(maquinariaLlenadoIds.get(i),names);
				funcionarioLlenadoIds.put(maquinariaLlenadoIds.get(i),funcionarioIds);

				maquinaLlenadoNames[i] = maquinasLlenado.get(maquinariaLlenadoIds.get(i)).get(1);
			}

			// setting up loteado maquinaria information

			String[] maquinaLoteadoNames = new String[maquinariaLoteadoIds.size()];

			funcionarioLoteadoNames = new HashMap<String,ArrayList<String>>();
			funcionarioLoteadoIds = new HashMap<String,ArrayList<String>>();

			for(int i=0;i<maquinariaLoteadoIds.size();i++) {
				ArrayList<String> funcionarioIds = db
						.retrieveFuncionarioCapacidadOperar(Integer
								.valueOf(maquinariaLoteadoIds.get(i)));

				ArrayList<String> names = new ArrayList<String>();

				for(int j=0;j<funcionarioIds.size();j++) {
					names.add(funcionarios.get(funcionarioIds.get(j)).get(2) + "," + funcionarios.get(funcionarioIds.get(j)).get(3));
				}

				funcionarioLoteadoNames.put(maquinariaLoteadoIds.get(i),names);
				funcionarioLoteadoIds.put(maquinariaLoteadoIds.get(i),funcionarioIds);

				maquinaLoteadoNames[i] = maquinasLoteado.get(maquinariaLoteadoIds.get(i)).get(1);
			}

			//rest of fases

			allFuncionarioNames = new ArrayList<String>();

			allFuncionarioIds = db.retrieveFuncionarioIds();

			for(int j=0;j<allFuncionarioIds.size();j++) {
				allFuncionarioNames.add(funcionarios.get(allFuncionarioIds.get(j)).get(2)+ "," + funcionarios.get(allFuncionarioIds.get(j)).get(3));
			}


			GridBagConstraints c = new GridBagConstraints();

			fasepanel = new ArrayList<ArrayList<JPanel>>();
			iniciotime = new ArrayList<ArrayList<JComboBox>>();
			fintime = new ArrayList<ArrayList<JComboBox>>();
			funcionariosList = new ArrayList<ArrayList<IndexedList>>();
			maquinasList = new ArrayList<ArrayList<IndexedList>>();
			finalizado = new ArrayList<ArrayList<JCheckBox>>();
			unidades = new ArrayList<ArrayList<JTextField>>();
			unidadesanteriores = new ArrayList<ArrayList<Integer>>();

			bandas = db.retrieveProductoRequiereBandas(plan.lotes.get(loteindex).getproductID());
			loteado = db.retrieveProductoRequiereLoteado(plan.lotes.get(loteindex).getproductID());
			etiquetado = db.retrieveProductoRequiereEtiquetado(plan.lotes.get(loteindex).getproductID());


			boolean firstadded = false;


			for(int i=0;i<7;i++) {


				fasepanel.add(new ArrayList<JPanel>());
				iniciotime.add(new ArrayList<JComboBox>());
				fintime.add(new ArrayList<JComboBox>());
				funcionariosList.add(new ArrayList<IndexedList>());
				maquinasList.add(new ArrayList<IndexedList>());
				finalizado.add(new ArrayList<JCheckBox>());
				unidades.add(new ArrayList<JTextField>());
				unidadesanteriores.add(new ArrayList<Integer>());
				//funcionariosList.add(new ArrayList<IndexedList>());
				//maquinasList.add(new ArrayList<IndexedList>());

				if((i==3 && loteado) || (i==4 && etiquetado) || (i==5 && bandas) 
						||
						(i<3 || i>5)) {

					////System.out.println("entro i=" + i);

					int fasecount = 0;

					loweredbevel = BorderFactory.createLoweredBevelBorder();

					border = BorderFactory.createTitledBorder(loweredbevel,
							"Informacion de " + fasenames[i]);

					grayborder = BorderFactory
							.createLineBorder(Color.LIGHT_GRAY);

					modlotefasespanel.setLayout(new BoxLayout(modlotefasespanel, BoxLayout.Y_AXIS));


					fasepanel.get(i).add(new JPanel(new GridBagLayout()));

					fasepanel.get(i).get(fasecount).setBorder(border);


					JPanel iniciopanel = new JPanel(new BorderLayout());
					JLabel iniciolabel = new JLabel("Hora inicio");

					SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");
					String firsttime = "07:00";
					String startalm = "11:54";
					String endalm = "13:00";
					String endtime = "18:00";
					Calendar cal = Calendar.getInstance();
					Calendar startalmcal = Calendar.getInstance();
					Calendar endalmcal = Calendar.getInstance();
					Calendar endcal = Calendar.getInstance();

					try {
						cal.setTime(formatter.parse(firsttime));
						endcal.setTime(formatter.parse(endtime));
						startalmcal.setTime(formatter.parse(startalm));
						endalmcal.setTime(formatter.parse(endalm));
					} catch (ParseException e1) {
						e1.printStackTrace();
					}

					Vector time = new Vector();
					Vector time2 = new Vector();

					time.addElement(formatter.format(cal.getTime()));
					time2.addElement(formatter.format(cal.getTime()));

					while (cal.before(startalmcal)) {
						cal.add(Calendar.MINUTE, 6);
						time.addElement(formatter.format(cal.getTime()));
						time2.addElement(formatter.format(cal.getTime()));
					}
					
					cal.add(Calendar.MINUTE, 6);
					time2.addElement(formatter.format(cal.getTime()));
					
					while (cal.before(endalmcal)) {
						cal.add(Calendar.MINUTE, 6);
					}
					
					time.addElement(formatter.format(cal.getTime()));
					
					while (cal.before(endcal)) {
						cal.add(Calendar.MINUTE, 6);
						time.addElement(formatter.format(cal.getTime()));
						time2.addElement(formatter.format(cal.getTime()));
						
					}

					iniciotime.get(i).add(new JComboBox(time));
					iniciotime.get(i).get(fasecount).addActionListener(this);
					iniciotime.get(i).get(fasecount).setName("time:inicio:"+i);
					//iniciotime.get(i).get(fasecount).setActionCommand("time:inicio:"+i);

					int horainicio = 0;
					if(fases[i] != -1)
						horainicio = plan.lotes.get(loteindex).retrieveFaseStart(i+1, day, 0,true);

					//TODO
					if(horainicio>=60)
						horainicio = horainicio - 10;

					iniciotime.get(i).get(fasecount).setSelectedIndex(horainicio);

					iniciopanel.add(iniciolabel,BorderLayout.LINE_START);
					iniciopanel.add(iniciotime.get(i).get(fasecount),BorderLayout.AFTER_LINE_ENDS);

					c = new GridBagConstraints();

					c.anchor = GridBagConstraints.WEST;
					c.weightx = 0.5;
					//c.fill = GridBagConstraints.HORIZONTAL;
					c.gridx = 0;
					c.gridy = 1;

					fasepanel.get(i).get(fasecount).add(iniciopanel, c);

					JPanel finpanel = new JPanel(new BorderLayout());
					//finpanel.setBorder(grayborder);
					JLabel finlabel = new JLabel("Hora fin");

					fintime.get(i).add(new JComboBox(time2));
					fintime.get(i).get(fasecount).addActionListener(this);
					fintime.get(i).get(fasecount).setName("time:fin:"+i);

					int horafin = 0;
					if(fases[i] != -1)
						horafin = plan.lotes.get(loteindex).retrieveFaseEnd(i+1, day, 0,true) +1;
					
					if(horafin>60)
						horafin = horafin - 10;

					fintime.get(i).get(fasecount).setSelectedIndex(horafin);

					finpanel.add(finlabel,BorderLayout.LINE_START);
					finpanel.add(fintime.get(i).get(fasecount),BorderLayout.AFTER_LINE_ENDS);

					c = new GridBagConstraints();

					c.anchor = GridBagConstraints.WEST;
					c.weightx = 0.5;
					//c.fill = GridBagConstraints.HORIZONTAL;
					c.gridx = 1;
					c.gridy = 1;

					fasepanel.get(i).get(fasecount).add(finpanel, c);

					JPanel listPanel = new JPanel(new GridLayout(0,2));

					JPanel maquinaPanel = new JPanel(new BorderLayout());
					//maquinaPanel.setPreferredSize(new Dimension(200, 200));
					//maquinaPanel.setBorder(grayborder);
					JLabel maquinaLabel = new JLabel("Maquinaria");


					int selmaqprod = 0, selmaqllen = 0, selmaqlot = 0;
					if(i==1 || i==2 || i==3) {

						if(i==1) {
							//plan.lotes.get(fases[i]).
							maquinasList.get(i).add(new IndexedList(new DefaultListModel(),maquinaProduccionNames,maquinariaProduccionIds,1));
							String maquinaria = maquinariaProduccionIds.get(0);
							//if(fases[i] != -1)
							maquinaria = plan.lotes.get(loteindex).retrieveFaseMaquinaria(i+1,day,0);

							for(int j=0;j<maquinariaProduccionIds.size();j++) {
								if(maquinariaProduccionIds.get(j).equals(maquinaria)) {
									maquinasList.get(i).get(fasecount).setSelectedIndex(j);
									selmaqprod = j;
									break;
								}
							}


						}
						if(i==2) {
							maquinasList.get(i).add(new IndexedList(new DefaultListModel(),maquinaLlenadoNames,maquinariaLlenadoIds,2));

							String maquinaria = maquinariaLlenadoIds.get(0);
							if(fases[i] != -1)
								maquinaria = plan.lotes.get(loteindex).retrieveFaseMaquinaria(i+1,day,0);

							for(int j=0;j<maquinariaLlenadoIds.size();j++) {
								if(maquinariaLlenadoIds.get(j).equals(maquinaria)) {
									maquinasList.get(i).get(fasecount).setSelectedIndex(j);
									selmaqllen = j;
									break;
								}
							}
						}
						else if(i==3) {
							maquinasList.get(i).add(new IndexedList(new DefaultListModel(),maquinaLoteadoNames,maquinariaLoteadoIds,3));

							String maquinaria = maquinariaLoteadoIds.get(0);
							if(fases[i] != -1)
								maquinaria = plan.lotes.get(loteindex).retrieveFaseMaquinaria(i+1,day,0);

							for(int j=0;j<maquinariaLoteadoIds.size();j++) {
								if(maquinariaLoteadoIds.get(j).equals(maquinaria)) {
									maquinasList.get(i).get(fasecount).setSelectedIndex(j);
									selmaqlot = j;
									break;
								}
							}
						}

						maquinasList.get(i).get(fasecount).setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
						//maquinasList.get(i).setSelectedIndex(0);


						maquinasList.get(i).get(fasecount).setFixedCellWidth(150);
						maquinasList.get(i).get(fasecount).setVisibleRowCount(5);
						maquinasList.get(i).get(fasecount).setName("maquinas:"+i);
						maquinasList.get(i).get(fasecount).addListSelectionListener(this);

						JScrollPane scrollpane = new JScrollPane(maquinasList.get(i).get(fasecount));

						maquinaPanel.add(maquinaLabel,BorderLayout.NORTH);
						//maquinaPanel.add(scrollpane,BorderLayout.CENTER);
						listPanel.add(scrollpane);

						/*if(i==1)
							maquinasList.get(1).get(fasecount).scrollRectToVisible(maquinasList.get(1).get(fasecount).getCellBounds(
									maquinasList.get(1).get(fasecount).getSelectedIndex(),
									maquinasList.get(1).get(fasecount).getSelectedIndex()+3));*/
					}
					else {
						maquinasList.get(i).add(new IndexedList(new DefaultListModel(),i));
						maquinasList.get(i).get(fasecount).setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
						maquinasList.get(i).get(fasecount).setSelectedIndex(0);

						maquinasList.get(i).get(fasecount).setFixedCellWidth(150);
						maquinasList.get(i).get(fasecount).setFixedCellHeight(20);
						maquinasList.get(i).get(fasecount).setVisibleRowCount(5);
						maquinasList.get(i).get(fasecount).setEnabled(false);

						JScrollPane scrollpane = new JScrollPane(maquinasList.get(i).get(fasecount));

						maquinaPanel.add(maquinaLabel,BorderLayout.NORTH);
						//maquinaPanel.add(scrollpane,BorderLayout.CENTER);
						listPanel.add(scrollpane);
					}



					c = new GridBagConstraints();

					c.weightx = 0.5;
					c.anchor = GridBagConstraints.WEST;
					c.insets = new Insets(10,0,0,0);
					c.gridx = 0;
					c.gridy = 2;

					fasepanel.get(i).get(fasecount).add(maquinaPanel, c);

					JPanel funcionariosPanel = new JPanel(new BorderLayout());
					JLabel funcionariosLabel = new JLabel("Funcionarios");



					if(i==1 || i==2 || i==3) {

						funcionariosList.get(i).add(new IndexedList(new DefaultListModel(),i));
						////System.out.println("funcionariospane check " + i);
						funcionariospane.add(new JScrollPane(funcionariosList.get(i).get(fasecount)));
						ArrayList<String> funcionarioIds = null;


						if(i==1) {
							funcionarioIds = funcionarioProduccionIds.get(maquinariaProduccionIds.get(selmaqprod));
							funcionariosList.get(i).get(fasecount).updateList(funcionarioProduccionNames.get(maquinariaProduccionIds.get(selmaqprod)),funcionarioIds);

							ArrayList<String> personal = null;
							if(fases[i] != -1)
								personal = plan.lotes.get(loteindex).retrieveFasePersonal(i+1,day,0);
							else {
								personal = new ArrayList<String>();
								personal.add(funcionarioIds.get(0));
							}

							int[] selectedindices = new int[personal.size()];
							for(int j=0;j<personal.size();j++) {
								for(int k=0;k<funcionarioIds.size();k++) {
									if(funcionarioIds.get(k).equals(personal.get(j))) {
										selectedindices[j] = k;
										break;
									}
								}
							}
							funcionariosList.get(i).get(fasecount).setSelectedIndices(selectedindices);
						}
						else if(i==2) {
							funcionarioIds = funcionarioLlenadoIds.get(maquinariaLlenadoIds.get(selmaqllen));
							funcionariosList.get(i).get(fasecount).updateList(funcionarioLlenadoNames.get(maquinariaLlenadoIds.get(selmaqllen)),funcionarioIds);

							ArrayList<String> personal = null;
							if(fases[i] != -1)
								personal = plan.lotes.get(loteindex).retrieveFasePersonal(i+1,day,0);
							else {
								personal = new ArrayList<String>();
								personal.add(funcionarioIds.get(0));
							}

							int[] selectedindices = new int[personal.size()];
							for(int j=0;j<personal.size();j++) {
								for(int k=0;k<funcionarioIds.size();k++) {
									if(funcionarioIds.get(k).equals(personal.get(j))) {
										selectedindices[j] = k;
										break;
									}
								}
							}
							funcionariosList.get(i).get(fasecount).setSelectedIndices(selectedindices);
						}
						else  if(i==3){
							funcionarioIds = funcionarioLoteadoIds.get(maquinariaLoteadoIds.get(selmaqlot));
							funcionariosList.get(i).get(fasecount).updateList(funcionarioLoteadoNames.get(maquinariaLoteadoIds.get(selmaqlot)),funcionarioIds);

							ArrayList<String> personal = null;
							if(fases[i] != -1)
								personal = plan.lotes.get(loteindex).retrieveFasePersonal(i+1,day,0);
							else {
								personal = new ArrayList<String>();
								personal.add(funcionarioIds.get(0));
							}

							int[] selectedindices = new int[personal.size()];
							for(int j=0;j<personal.size();j++) {
								for(int k=0;k<funcionarioIds.size();k++) {
									if(funcionarioIds.get(k).equals(personal.get(j))) {
										selectedindices[j] = k;
										break;
									}
								}
							}
							funcionariosList.get(i).get(fasecount).setSelectedIndices(selectedindices);
						}

						//funcionariospane = new JScrollPane(funcionariosList);
					}
					else {
						funcionariosList.get(i).add(new IndexedList(new DefaultListModel(),i));
						funcionariosList.get(i).get(fasecount).updateList(allFuncionarioNames,allFuncionarioIds);

						ArrayList<String> personal = null;
						if(fases[i] != -1)
							personal = plan.lotes.get(loteindex).retrieveFasePersonal(i+1,day,0);
						else {
							personal = new ArrayList<String>();
							personal.add(allFuncionarioIds.get(0));
						}

						int[] selectedindices = new int[personal.size()];
						for(int j=0;j<personal.size();j++) {
							for(int k=0;k<allFuncionarioIds.size();k++) {
								if(allFuncionarioIds.get(k).equals(personal.get(j))) {
									selectedindices[j] = k;
									break;
								}
							}
						}

						funcionariosList.get(i).get(fasecount).setSelectedIndices(selectedindices);
						////System.out.println("funcionariospane check " + i);
						funcionariospane.add(new JScrollPane(funcionariosList.get(i).get(fasecount)));
						//listPanel.add(new JScrollPane(funcionariosList.get(i)));
					}

					funcionariosList.get(i).get(fasecount).setFixedCellWidth(150);
					funcionariosList.get(i).get(fasecount).setVisibleRowCount(5);
					funcionariosList.get(i).get(fasecount).setName("funcionarios:"+i);
					funcionariosList.get(i).get(fasecount).addListSelectionListener(this);

					funcionariosPanel.add(funcionariosLabel,BorderLayout.NORTH);
					//funcionariosPanel.add(funcionariospane.get(i),BorderLayout.CENTER);
					listPanel.add(funcionariospane.get(i));

					c = new GridBagConstraints();

					c.weightx = 0.5;
					c.anchor = GridBagConstraints.WEST;
					c.insets = new Insets(10,0,0,0);
					c.gridx = 1;
					c.gridy = 2;

					fasepanel.get(i).get(fasecount).add(funcionariosPanel, c);

					c = new GridBagConstraints();

					c.weightx = 1;
					c.anchor = GridBagConstraints.WEST;
					c.gridwidth = 2;
					c.fill = GridBagConstraints.HORIZONTAL;
					c.gridy = 3;

					fasepanel.get(i).get(fasecount).add(listPanel, c);


					////////////////////////////////////////////////////////////////////////////////

					JPanel unidadespanel = new JPanel(new BorderLayout());
					JLabel unidadeslabel = new JLabel("Unidades");
					unidades.get(i).add(new JTextField());
					unidades.get(i).get(fasecount).addActionListener(this);
					unidades.get(i).get(fasecount).setActionCommand("unidades:"+i);


					int unidadesslot = plan.lotes.get(loteindex).getLoteUnidades();

					if(fases[i] != -1) {
						unidadesslot = plan.lotes.get(loteindex).getFaseUnidades(day,i+1);
						unidadesanteriores.get(i).add(plan.lotes.get(loteindex).getFaseUnidadesAnteriores(day,i+1));
					}
					else {
						unidadesanteriores.get(i).add(0);
					}
					unidades.get(i).get(fasecount).setText("" + unidadesslot);

					unidadespanel.add(unidadeslabel,BorderLayout.LINE_START);
					unidadespanel.add(unidades.get(i).get(fasecount),BorderLayout.AFTER_LINE_ENDS);

					c = new GridBagConstraints();

					c.weightx = 0.5;
					c.anchor = GridBagConstraints.WEST;
					c.insets = new Insets(10,0,0,0);
					c.gridx = 0;
					c.gridy = 4;

					fasepanel.get(i).get(fasecount).add(unidadespanel, c);

					////////////////////////////////////////////////////////////////////////////////


					JPanel finalizadopanel = new JPanel(new BorderLayout());
					//finalizadopanel.setBorder(grayborder);
					JLabel finalizadoLabel = new JLabel("Fase Finalizada");
					finalizado.get(i).add(new JCheckBox());
					finalizado.get(i).get(fasecount).addActionListener(this);
					finalizado.get(i).get(fasecount).setActionCommand("finalizado:"+i);


					boolean finalizada = false;

					if(fases[i] != -1)
						finalizada = plan.lotes.get(loteindex).isFaseFinalizada(i+1,day);

					finalizado.get(i).get(fasecount).setSelected(finalizada);

					finalizadopanel.add(finalizadoLabel,BorderLayout.LINE_START);
					finalizadopanel.add(finalizado.get(i).get(fasecount),BorderLayout.AFTER_LINE_ENDS);

					c = new GridBagConstraints();

					//c.anchor = GridBagConstraints.EAST;
					c.weightx = 0.5;
					c.anchor = GridBagConstraints.WEST;
					c.insets = new Insets(10,0,0,0);
					c.gridx = 1;
					c.gridy = 4;

					fasepanel.get(i).get(fasecount).add(finalizadopanel, c);

					if(fases[i] != -1 /*&& i >= plan.lotes.get(loteindex).getStartingFase() - 1*/) {
						firstadded = true;
						fasesindex.add(i);
						currentfases.add(i);
						if(currentfases.size()!=1) {
							finalizado.get(currentfases.get(currentfases.size()-2)).get(0).setEnabled(false);
						}

						fasespanelindex++;
						fasepanel.get(i).get(0).setVisible(true);
						fasepanel.get(i).get(0).setEnabled(true);
						modlotefasespanel.add(fasepanel.get(i).get(0));
						//defaultpanel.setEnabled(true);
						//defaultpanel.setVisible(true);
					}
					else if(firstadded){
						fasesagregarindex.add(i);
						fasesagregarpanelindex++;
						fasepanel.get(i).get(0).setVisible(false);
						fasepanel.get(i).get(0).setEnabled(false);
						modlotefasespanel.add(fasepanel.get(i).get(0));
					}
					////System.out.println("fasepanelindex = " + fasepanelindex);

					////System.out.println("fasepanelindex = " + fasespanelindex);
					///////////////////////////////////////////////////////////////////////////////
				}
				else {

					//funcionariosList.get(i).add(new IndexedList(new DefaultListModel(),i));
					//maquinasList.add(new IndexedList(new DefaultListModel(),i));
					funcionariospane.add(new JScrollPane());
				}

			}



			if(fasesindex.size()==0) {
				int startadding = 0;
				int lastfase = plan.lotes.get(loteindex).lastFaseFinalizada(day);
				if(!(lastfase == -1)) {
					startadding = lastfase;
				}
				else if(lastfase == -1 && plan.lotes.get(loteindex).getStartingFase() > 1) {
					startadding = plan.lotes.get(loteindex).getStartingFase() - 1;
				}
				////System.out.println("startadding = " + startadding);
				for(int i = 0; i< 7; i++) {
					if((i==3 && loteado) || (i==4 && etiquetado) || (i==5 && bandas) 
							||
							(i<3 || i>5)) {
						if(i >= startadding){
							fasesagregarindex.add(i);
							//currentfases.add(i);
							/*if(currentfases.size()!=1) {
								//finalizado.get(currentfases.get(currentfases.size()-1)).get(0).setEnabled(true);
								finalizado.get(currentfases.get(currentfases.size()-2)).get(0).setEnabled(false);
							}*/
							fasesagregarpanelindex++;
							fasepanel.get(i).get(0).setVisible(false);
							fasepanel.get(i).get(0).setEnabled(false);
							modlotefasespanel.add(fasepanel.get(i).get(0));
						}
					}
				}
			}

			JPanel buttonPanel = new JPanel(new GridBagLayout());

			borrarfase = new JButton("Borrar Ultima Fase");
			agregarfase = new JButton("Agregar Siguiente Fase");

			borrarfase.addActionListener(this);
			agregarfase.addActionListener(this);

			borrarfase.setActionCommand(Constants.CONFIRMAR_MOSTRAR_ELIMINAR_FASE);
			agregarfase.setActionCommand(Constants.CONFIRMAR_MOSTRAR_AGREGAR_FASE);

			c = new GridBagConstraints();

			c.insets = new Insets(15,0,15,0);
			c.weightx = 0.5;
			c.anchor = GridBagConstraints.CENTER;
			c.gridx = 0;
			c.gridy = 0;


			buttonPanel.add(borrarfase,c);

			c = new GridBagConstraints();

			c.insets = new Insets(15,0,15,0);
			c.weightx = 0.5;
			c.anchor = GridBagConstraints.CENTER;
			c.gridx = 1;
			c.gridy = 0;

			buttonPanel.add(agregarfase,c);
			buttonPanel.setBorder(grayborder);

			modlotepanel.add(buttonPanel);

			JPanel confirmarbuttonpanel = new JPanel(new GridBagLayout());
			JButton cancelarbutton = new JButton("Cancelar",redicon);
			cancelarbutton.addActionListener(this);
			cancelarbutton.setActionCommand(Constants.CONFIRMAR_CANCELAR_MODIFICAR_LOTE);

			c = new GridBagConstraints();

			c.insets = new Insets(15,0,15,0);
			c.weightx = 0.25;
			c.anchor = GridBagConstraints.CENTER;
			c.gridx = 0;
			c.gridy = 0;

			confirmarbuttonpanel.add(cancelarbutton, c);

			JButton confirmarbutton = new JButton("Confirmar",greenicon);
			confirmarbutton.addActionListener(this);
			confirmarbutton.setActionCommand(Constants.CONFIRMAR_MODIFICAR_LOTE);

			c = new GridBagConstraints();

			c.insets = new Insets(15,0,15,0);
			c.weightx = 0.25;
			c.anchor = GridBagConstraints.CENTER;
			c.gridx = 1;
			c.gridy = 0;

			confirmarbuttonpanel.add(confirmarbutton, c);

			modlotepanel.add(confirmarbuttonpanel);


			// contentPane.add(listform, BorderLayout.LINE_END);

			if(fasespanelindex ==0) {
				setFasesVisible(false);
			}
			setup = true;

			//modlotefasespanel.setPreferredSize(new Dimension(modlotefasespanel.getWidth(),800));
			//modlotefasespanel.revalidate();

			contentPane.add(modlotepanel, BorderLayout.NORTH);

			modlotefasespanel.revalidate();
			jsp.revalidate();
			pack();
			height = jsp.getSize().height;
			if(height > scrnsize.height - 200)
				height = scrnsize.height - 200;
			width = jsp.getSize().width+20+((currentfases.size()==0)?(360):(0));

			jsp.setPreferredSize(new Dimension(width,height));
			modlotepanel.revalidate();

			pack();

			setVisible(true);


		}

		public void actionPerformed(ActionEvent e) {

			ArrayList<String> mensualData = new ArrayList<String>();

			String command = e.getActionCommand();



			if (command == Constants.CONFIRMAR_MOSTRAR_ELIMINAR_FASE) {

				////System.out.println("fasepanelindex = " + fasesindex.get(fasespanelindex-1));
				//fasepanel.get(0).get(0).setVisible(false);
				if(fasesagregarpanelindex != fasesagregarindex.size()) {
					fasesagregarpanelindex++;
					fasepanel.get(fasesagregarindex.get(fasesagregarindex.size()-fasesagregarpanelindex)).get(0).setEnabled(false);
					fasepanel.get(fasesagregarindex.get(fasesagregarindex.size()-fasesagregarpanelindex)).get(0).setVisible(false);
					currentfases.remove(fasesagregarindex.get(fasesagregarindex.size()-fasesagregarpanelindex));
					toberemovedfases.add(fasesagregarindex.get(fasesagregarindex.size()-fasesagregarpanelindex));
					if(currentfases.size()!=0) 
						finalizado.get(currentfases.get(currentfases.size()-1)).get(0).setEnabled(true);

					if(fasesagregarpanelindex == fasesagregarindex.size() 
							&& fasespanelindex == 0) {
						setFasesVisible(false);
					}


					int height = (currentfases.size()*220)+20;
					if(height > scrnsize.height - 200)
						height = scrnsize.height - 200;

					jsp.setPreferredSize(new Dimension(width,height));
					modlotepanel.revalidate();

					pack();
				}
				else if(fasespanelindex!=0) {
					fasepanel.get(fasesindex.get(fasespanelindex-1)).get(0).setEnabled(false);
					fasepanel.get(fasesindex.get(fasespanelindex-1)).get(0).setVisible(false);
					currentfases.remove(fasesindex.get(fasespanelindex-1));
					toberemovedfases.add(fasesindex.get(fasespanelindex-1));
					if(currentfases.size()!=0) 
						finalizado.get(currentfases.get(currentfases.size()-1)).get(0).setEnabled(true);
					//modlotefasespanel.remove(fasepanel.get(fasesindex.get(fasespanelindex-1)).get(0));
					fasespanelindex--;					
					if(fasespanelindex == 0) {
						setFasesVisible(false);
					}



					int height = (currentfases.size()*225)+15;
					if(height > scrnsize.height - 200)
						height = scrnsize.height - 200;

					jsp.setPreferredSize(new Dimension(width,height));
					modlotepanel.revalidate();

					pack();
				}

			} else if(command == Constants.CONFIRMAR_MOSTRAR_AGREGAR_FASE){

				boolean allfases = false;

				int lastfin = 0;

				//System.out.println("currentfasesize="+currentfases.size());



				////System.out.println("lastfin=" + lastfin);

				if(fasespanelindex==fasesindex.size() && fasesagregarpanelindex == 0) {
					allfases = true;
					JOptionPane
					.showMessageDialog(
							new JFrame(),
							"Todas las fases de produccion posibles\n" +
									"del lote ya fueron agregadas",
									"Mensaje de Error",
									JOptionPane.ERROR_MESSAGE);
				}
				else {

					if(currentfases.size()>0) {
						////System.out.println("currentfasesize="+currentfases.size());
						////System.out.println("lote="+plan.lotes.get(loteindex).getproductName() + ":" + plan.lotes.get(loteindex).getLoteUnidades());
						lastfin = fintime.get(currentfases.get(currentfases.size()-1)).get(0).getSelectedIndex();
					}

					if(lastfin < 110) {

						if(!(fasespanelindex==fasesindex.size())) {
							fasespanelindex++;
							fasepanel.get(fasesindex.get(fasespanelindex-1)).get(0).setEnabled(true);
							fasepanel.get(fasesindex.get(fasespanelindex-1)).get(0).setVisible(true);
							currentfases.add(fasesindex.get(fasespanelindex-1));
							toberemovedfases.remove(fasesindex.get(fasespanelindex-1));
							if(currentfases.size()!=1) {
								finalizado.get(currentfases.get(currentfases.size()-2)).get(0).setEnabled(false);
								finalizado.get(currentfases.get(currentfases.size()-2)).get(0).setSelected(true);
							}
							setFasesVisible(true);
							int height = (currentfases.size()*225)+15;
							if(height > scrnsize.height - 200)
								height = scrnsize.height - 200;

							jsp.setPreferredSize(new Dimension(width,height));
							modlotepanel.revalidate();

							pack();
						}
						else if(fasesagregarpanelindex != 0) {
							if(fasepanel.get(fasesagregarindex.get(fasesagregarindex.size()-fasesagregarpanelindex)).size() > 0) {
								fasepanel.get(fasesagregarindex.get(fasesagregarindex.size()-fasesagregarpanelindex)).get(0).setEnabled(true);
								fasepanel.get(fasesagregarindex.get(fasesagregarindex.size()-fasesagregarpanelindex)).get(0).setVisible(true);
								currentfases.add(fasesagregarindex.get(fasesagregarindex.size()-fasesagregarpanelindex));
								toberemovedfases.remove(fasesagregarindex.get(fasesagregarindex.size()-fasesagregarpanelindex));
								fasesagregarpanelindex--;
								setup = false;
								iniciotime.get(currentfases.get(currentfases.size()-1)).get(0).setSelectedIndex(lastfin);
								fintime.get(currentfases.get(currentfases.size()-1)).get(0).setSelectedIndex(lastfin+1);
								setup = true;
								if(currentfases.size()!=1) {
									finalizado.get(currentfases.get(currentfases.size()-2)).get(0).setEnabled(false);
									finalizado.get(currentfases.get(currentfases.size()-2)).get(0).setSelected(true);
								}
								setFasesVisible(true);

								int height = (currentfases.size()*225)+15;
								if(height > scrnsize.height - 200)
									height = scrnsize.height - 200;

								jsp.setPreferredSize(new Dimension(width,height));
								modlotepanel.revalidate();

								pack();
							}
						}
					}
					else {
						JOptionPane
						.showMessageDialog(
								new JFrame(),
								"No hay tiempo para agregar una fase\n" + 
										"adicional este dia",
										"Mensaje de Error",
										JOptionPane.ERROR_MESSAGE);
					}
				}
			} 
			else if("comboBoxChanged".equals(command)) {

				JComboBox combo = (JComboBox) e.getSource();


				if(setup) {
					String array[] = combo.getName().split(":");

					int index = Integer.valueOf(array[2]); 
					int currentindex = 0;

					for(int i=0;i<currentfases.size();i++) {
						if(currentfases.get(i)==index) {
							currentindex = i;
							break;
						}
					}

					int inicio = iniciotime.get(index).get(0).getSelectedIndex();
					int fin = fintime.get(index).get(0).getSelectedIndex();
					int finanterior = 0;
					int iniciosiguiente = 110;
					////System.out.println("index="+currentindex + ":size=" + currentfases.size() );
					if(currentindex>0) {
						finanterior = fintime.get(currentfases.get(currentindex-1)).get(0).getSelectedIndex();
					}
					if(currentindex<currentfases.size()-1) {
						iniciosiguiente = iniciotime.get(currentfases.get(currentindex+1)).get(0).getSelectedIndex();
					}


					if(inicio>=fin) {
						if(array[1].equals("inicio")) {
							combo.setSelectedIndex(fin-1);
						}
						else{
							combo.setSelectedIndex(inicio+1);
						}
						JOptionPane
						.showMessageDialog(
								new JFrame(),
								"hora de inicio no puede ser mayor o igual que la de final",
								"Mensaje de Error",
								JOptionPane.ERROR_MESSAGE);
					}
					else if(array[1].equals("inicio")) {
						if(inicio<finanterior) {
							combo.setSelectedIndex(finanterior);
							JOptionPane
							.showMessageDialog(
									new JFrame(),
									"hora de inicio no puede ser menor a hora final de fase anterior",
									"Mensaje de Error",
									JOptionPane.ERROR_MESSAGE);
						}
					}
					else if(array[1].equals("fin")) {
						if(fin>iniciosiguiente) {
							combo.setSelectedIndex(iniciosiguiente);
							JOptionPane
							.showMessageDialog(
									new JFrame(),
									"hora de fin no puede ser mayor a hora de inicio de proxima fase",
									"Mensaje de Error",
									JOptionPane.ERROR_MESSAGE);
						}
					}
				}

			}
			else if(command.startsWith("finalizado")) {
				String array[] = command.split(":");

				if(setup) {
					int index = Integer.valueOf(array[1]);
					if(currentfases.get(currentfases.size()-1)==index){
						//JCheckBox last = (JCheckBox) e.getSource();
						//System.out.println("index" + index + " status " + finalizado.get(index).get(0).isSelected());
						for(int i=0;i<currentfases.size()-2;i++) {
							finalizado.get(currentfases.get(i)).get(0).setSelected(true);
							finalizado.get(currentfases.get(i)).get(0).setEnabled(false);
						}

					}
				}
			}
			else if (command == Constants.CONFIRMAR_MODIFICAR_LOTE) {

				String array[] = ((String) monthsCombo.getSelectedItem()).split("/");

				boolean personalselectedcheck = false;
				boolean finalizacionyunidadescheck = false;
				boolean unidadesmaxcheck = false;
				boolean unidadesmincheck = false;

				int fasemessage;
				int personalmin = 0;
				int personalmax = 0;
				int fallo = 0;

				if(currentfases.size() == 0) {
					personalselectedcheck = true;
					finalizacionyunidadescheck = true;
					unidadesmaxcheck = true;
					unidadesmincheck = true;
				}

				for(int i =0; i<currentfases.size(); i++) {

					int anteriores = unidadesanteriores.get(currentfases.get(i)).get(0);
					int unidadeslote = plan.lotes.get(loteindex).getLoteUnidades();
					int current = Integer.valueOf(unidades.get(currentfases.get(i)).get(0).getText());
					boolean finalizadofase = finalizado.get(currentfases.get(i)).get(0).isSelected();

					int selections = funcionariosList.get(currentfases.get(i)).get(0).getSelectedIndices().length;


					if(currentfases.get(i)==0 || currentfases.get(i)==1) {
						if(selections==2) 
							personalselectedcheck = true;
						else {
							personalselectedcheck = false;
							fallo = currentfases.get(i);
							personalmin = 2;
							personalmax = 2;
							i=currentfases.size();
						}
					}
					else if(currentfases.get(i)==2 || currentfases.get(i)==3) {
						int funcionariosnecesarios = db
								.retrieveMaquinariaNumFuncionarios(Integer
										.valueOf(maquinasList.get(currentfases.get(i)).get(0).getValues().get(0)));
						if(selections==funcionariosnecesarios) {
							personalselectedcheck = true;
						}
						else {
							personalselectedcheck = false;
							fallo = currentfases.get(i);
							personalmin = funcionariosnecesarios;
							personalmax = funcionariosnecesarios;
							i=currentfases.size();
						}

					}
					else if(currentfases.get(i)==4) {
						if(selections >= 2 && selections <= 5) {
							personalselectedcheck = true;
						}
						else {
							personalselectedcheck = false;
							fallo = currentfases.get(i);
							personalmin = 2;
							personalmax = 5;
							i=currentfases.size();
						}
					}
					else if(currentfases.get(i)==5) {
						if(selections >= 3 && selections <= 6)
							personalselectedcheck = true;
						else {
							personalselectedcheck = false;
							fallo = currentfases.get(i);
							personalmin = 3;
							personalmax = 6;
							i=currentfases.size();
						}
					}
					else if(currentfases.get(i)==6) {
						if(selections >= 2 && selections <= 8) {
							personalselectedcheck = true;
						}
						else {
							personalselectedcheck = false;
							fallo = currentfases.get(i);
							personalmin = 2;
							personalmax = 8;
							i=currentfases.size();
						}
					}
					if(personalselectedcheck) {

						if(finalizadofase) {
							if(current + anteriores == unidadeslote) {
								finalizacionyunidadescheck = true;
							}
							else {
								finalizacionyunidadescheck = false;
								fallo = currentfases.get(i);
								i=currentfases.size();
							}
						}
						else {
							if(current + anteriores == unidadeslote) {
								finalizacionyunidadescheck = false;
								fallo = currentfases.get(i);
								i=currentfases.size();
							}
							else {
								finalizacionyunidadescheck = true;
							}
						}

						if(finalizadofase) {
							if(current == 0) {
								unidadesmincheck = false;
								fallo = currentfases.get(i);
								i=currentfases.size();
							}
							else 
								unidadesmincheck = true;
	
							if(current > unidadeslote + anteriores && unidadesmincheck && finalizadofase && personalselectedcheck) {
								unidadesmaxcheck = false;
								fallo = currentfases.get(i);
								i=currentfases.size();
							}
							else 
								unidadesmaxcheck = true;
						}

					}
				}

				if(personalselectedcheck 
						&& finalizacionyunidadescheck
						&& unidadesmincheck
						&& unidadesmaxcheck) {



					String fecha[] = ((String) monthsCombo.getSelectedItem()).split("/");

					//System.out.println("tobe removed fases = " + toberemovedfases.size());
					//System.out.println("current fases = " + currentfases.size());
					for(int i =0; i<toberemovedfases.size(); i++) {
						plan.lotes.get(loteindex).clearSlots(Integer.valueOf(fecha[0]),toberemovedfases.get(i)+1,0);
					}

					for(int i =0; i<currentfases.size(); i++) {

						Planner.Slot currslot = null;

						if(currentfases.get(i) == 0) {
							plan.lotes.get(loteindex).initDispensacion(day);
							currslot = plan.lotes.get(loteindex).getSlot(day,currentfases.get(i)+1,0);
						}
						else if(currentfases.get(i) == 1) {
							plan.lotes.get(loteindex).initProduccion(day);
							currslot = plan.lotes.get(loteindex).getSlot(day,currentfases.get(i)+1,0);
						}
						else {
							currslot = plan.lotes.get(loteindex).getSlot(day,currentfases.get(i)+1,0);
						}

						String[] selectedvalues = Arrays.copyOf(funcionariosList.get(currentfases.get(i)).get(0).getSelectedValues(), 
								funcionariosList.get(currentfases.get(i)).get(0).getSelectedValues().length, String[].class);

						ArrayList<String> wordList = new ArrayList<String>( 
								Arrays.asList(selectedvalues));

						/*if(i==0 && currslot==null) {
								plan.lotes.get(loteindex).clearLoteSlots();
							}*/

						int anteriores = unidadesanteriores.get(currentfases.get(i)).get(0);
						int unidadeslote = plan.lotes.get(loteindex).getLoteUnidades();
						int current = Integer.valueOf(unidades.get(currentfases.get(i)).get(0).getText());

						//modifying start time of lote
						if(currentfases.get(i) == 0) { 
							plan.lotes.get(loteindex).modifyStartTimeLote(
									iniciotime.get(currentfases.get(i)).get(0).getSelectedIndex());
						}

						if(currslot!=null) {

							currslot.modifyTimes(iniciotime.get(currentfases.get(i)).get(0).getSelectedIndex(), 
									fintime.get(currentfases.get(i)).get(0).getSelectedIndex()-1);



							if(currentfases.get(i) == 1
									|| currentfases.get(i) == 2
									|| currentfases.get(i) == 3) { 

								currslot.modifyMaquinaria(
										maquinasList.get(currentfases.get(i)).get(0).getValues().get(0)
										,maquinasList.get(currentfases.get(i)).get(0).getSelectedValue().toString());
							}

							currslot.modifyPersonal(
									funcionariosList.get(currentfases.get(i)).get(0).getValues()
									,wordList);

							currslot.modifyFinalizacion(finalizado.get(currentfases.get(i)).get(0).isSelected());

							currslot.modifyUnidades(anteriores, current, unidadeslote-anteriores-current);
						}
						else {

							if(currentfases.get(i) == 2
									|| currentfases.get(i) == 3) { 

								plan.lotes.get(loteindex).clearSlots(Integer.valueOf(fecha[0]),currentfases.get(i)+1,0);
								plan.lotes.get(loteindex).addSlot(day,fecha[2],fecha[1],
										iniciotime.get(currentfases.get(i)).get(0).getSelectedIndex(),
										fintime.get(currentfases.get(i)).get(0).getSelectedIndex()-1,
										maquinasList.get(currentfases.get(i)).get(0).getValues().get(0),
										maquinasList.get(currentfases.get(i)).get(0).getSelectedValue().toString(),
										funcionariosList.get(currentfases.get(i)).get(0).getValues(),
										wordList,
										currentfases.get(i)+1,
										finalizado.get(currentfases.get(i)).get(0).isSelected(),
										anteriores,
										current,
										unidadeslote-anteriores-current);
							}
							else {
								plan.lotes.get(loteindex).clearSlots(Integer.valueOf(fecha[0]),currentfases.get(i)+1,0);
								plan.lotes.get(loteindex).addSlot(day,fecha[2],fecha[1],
										iniciotime.get(currentfases.get(i)).get(0).getSelectedIndex(),
										fintime.get(currentfases.get(i)).get(0).getSelectedIndex()-1,
										null,
										null,
										funcionariosList.get(currentfases.get(i)).get(0).getValues(),
										wordList,
										currentfases.get(i)+1,
										finalizado.get(currentfases.get(i)).get(0).isSelected(),
										anteriores,
										current,
										unidadeslote-anteriores-current);
							}

						}

						if(currentfases.get(i) == 6) {
							if(plan.lotes.get(loteindex).isFinalizada(day,7)) {
								plan.lotes.get(loteindex).donedia = day;
								plan.lotes.get(loteindex).done = true;
								//db.modifyLoteisDone(loteindex, day, true);
							}
							else {
								//db.modifyLoteisDone(loteindex, 0, false);
								plan.lotes.get(loteindex).donedia = 0;
								plan.lotes.get(loteindex).done = false;
							}
						}

					}

					CardLayout cl = (CardLayout) (cards.getLayout());
					plan.printTable(day);
					parentpanel.createPlan(array[0], array[1], array[2], true);
					cl.show(cards, Constants.PlanLabel.GRID_PANEL.toString());
					modificado = true;
					this.dispose();
				}
				else if(!personalselectedcheck){
					String additionalclause = (personalmin!=personalmax)?(" - " + personalmax):"";
					JOptionPane
					.showMessageDialog(
							new JFrame(),
							"seleccione numero de personal adecuado (" + personalmin + additionalclause + ")"  + "\n" +
									"para la fase de " +  fasenames[fallo] ,
									"Mensaje de Error",
									JOptionPane.ERROR_MESSAGE);
				}
				else if(!finalizacionyunidadescheck){
					JOptionPane
					.showMessageDialog(
							new JFrame(),
							"Error en fase de " +  fasenames[fallo] + "\n\n" +
									"\"Seleccione numero de unidades acorde \n" +
									"al estatus de finalizacion de fase\""
									,
									"Mensaje de Error",
									JOptionPane.ERROR_MESSAGE);
				}
				else if(!unidadesmincheck){
					JOptionPane
					.showMessageDialog(
							new JFrame(),
							"Error en fase de " +  fasenames[fallo] + "\n\n" +
									"\"Seleccione numero de unidades minimas (1) \"",
									"Mensaje de Error",
									JOptionPane.ERROR_MESSAGE);
				}
				else if(!unidadesmaxcheck){
					JOptionPane
					.showMessageDialog(
							new JFrame(),
							"Error en fase de " +  fasenames[fallo] + "\n\n" +
									"\"Seleccione numero de unidades maximas \n" +
									"(unidades ya " + fasenames[fallo] + "unidades programadas \n" +
									"no deben exceder las unidades de lote\""
									,
									"Mensaje de Error",
									JOptionPane.ERROR_MESSAGE);
				}
			}
			else if(command.equals(Constants.CONFIRMAR_CANCELAR_MODIFICAR_LOTE)) {
				this.dispose();
			}

			/*//System.out.println("components in fases panel = " + modlotefasespanel.getComponentCount());
			for(int i=0;i<fasepanel.size();i++) {
				//System.out.println("i =" + i);
				if(fasepanel.get(i).size() > 0) {
					if(fasepanel.get(i).get(0).isVisible()) {
						//System.out.println("fasepanel =" + i + " is visible");
					}
				}
			}*/
		}

		@Override
		public void valueChanged(ListSelectionEvent e) {
			int funcindex = -1;

			IndexedList source = (IndexedList) e.getSource();
			String[] array = source.getName().split(":");

			if(array[0].equals("maquina")) {
				int maquinaindex = source.getIndex();
				////System.out.println("inside value changed = " + maquinaindex);
				if(!maquinasList.get(maquinaindex).get(0).isSelectionEmpty()) {
					////System.out.println("inside value changed = " + maquinaindex);
					int index = maquinasList.get(maquinaindex).get(0).getSelectedIndex();

					if(maquinaindex==1) {
						for(int i=0;i<funcionariosList.size();i++) {
							if(funcionariosList.get(i).get(0).getIndex() == maquinaindex) {
								funcindex = i;
								break;
							}	
						}

						////System.out.println("selected maquinaproduccion id first source = " + maquinariaProduccionIds.get(index));
						////System.out.println("selected maquinaproduccion id second source" + maquinasource.getValues());
						////System.out.println("index of funcionarios list" + funcionariosList.get(funcindex).get(0).getIndex());
						////System.out.println("selected funcionarios ids" + funcionariosList.get(funcindex).get(0).getValues());
						if(funcindex != -1)
							funcionariosList.get(funcindex).get(0).updateList(funcionarioProduccionNames.get(maquinariaProduccionIds.get(index)),funcionarioProduccionIds.get(maquinariaProduccionIds.get(index))); 
						// Updates the list automatically
					}
					else if(maquinaindex==2) {
						for(int i=0;i<funcionariosList.size();i++) {
							if(funcionariosList.get(i).get(0).getIndex() == maquinaindex) {
								funcindex = i;
								break;
							}	
						}
						if(funcindex != -1)
							funcionariosList.get(funcindex).get(0).updateList(funcionarioLlenadoNames.get(maquinariaLlenadoIds.get(index)),funcionarioLlenadoIds.get(maquinariaLlenadoIds.get(index))); 
						// Updates the list automatically
					}
					else if(maquinaindex==3) {
						for(int i=0;i<funcionariosList.size();i++) {
							if(funcionariosList.get(i).get(0).getIndex() == maquinaindex) {
								funcindex = i;
								break;
							}	
						}
						if(funcindex != -1)
							funcionariosList.get(funcindex).get(0).updateList(funcionarioLoteadoNames.get(maquinariaLoteadoIds.get(index)),funcionarioLoteadoIds.get(maquinariaLoteadoIds.get(index))); 
						// Updates the list automatically
					}
					else {
						// do nothing
					}

					if(funcindex != -1) {
						funcionariosList.get(funcindex).get(0).setSelectedIndex(0);

						// reset the view of the jscrollpane to the top by passing getcellbounds with index 0 and 2 which returns an object of type rectangle
						// which specifies the view in the jscrollpane relative to the jlist

						funcionariosList.get(funcindex).get(0).scrollRectToVisible(funcionariosList.get(maquinaindex).get(0).getCellBounds(0,2));
					}
				}
				/*else{
						if(array[1].equals("0")) {
							source.getSelecte
						}
					}*/
			}
		}

		public boolean getStatus() {
			return modificado;
		}



		public void setFasesVisible(boolean visibility) {
			modlotefasespanel.setVisible(visibility);
			jsp.setVisible(visibility);
			borrarfase.setEnabled(visibility);
			defaultpanel.setEnabled(!visibility);
			defaultpanel.setVisible(!visibility);
		}


	}
	public boolean getConfirmadoStatus() {
		return changestatus;
	}

	public void resetConfirmadoStatus() {
		if(mostrarButton!=null) {
			mostrarButton.setEnabled(true);
		}
		if(monthsCombo!=null) {
			monthsCombo.setEnabled(true);
		}
		if(yearCombo!=null) {
			yearCombo.setEnabled(true);
		}
		if(daysCombo!=null) {
			daysCombo.setEnabled(true);
		}
		changestatus = false;
	}

	public void updateStatus() {
		daysCombo.setEnabled(false);
		glassPanel.setVisible(true);

		if(tablescrollpane!=null) {
			tablescrollpane.setHorizontalScrollBarPolicy(HORIZONTAL_SCROLLBAR_NEVER);
			tablescrollpane.setVerticalScrollBarPolicy(VERTICAL_SCROLLBAR_NEVER);

		}
		daysCombo.removeActionListener(this);
		daysCombo.setSelectedIndex(0);
		daysCombo.addActionListener(this);

		buttonPanel.setEnabled(false);

		if(monthsCombo!=null) {
			monthsCombo.setEnabled(false);
		}
		if(yearCombo!=null) {
			yearCombo.setEnabled(false);
		}
		if(daysCombo!=null) {
			daysCombo.setEnabled(false);
		}
		if(agregarloteButton!=null) {
			agregarloteButton.setEnabled(false);
		}
		if(modificarloteButton!=null) {
			modificarloteButton.setEnabled(false);
		}
		if(eliminarloteButton!=null) {
			eliminarloteButton.setEnabled(false);
		}
		if(verificarPlanButton!=null) {
			verificarPlanButton.setEnabled(false);
		}
		if(databaseButton!=null) {
			databaseButton.setEnabled(false);
		}

		if(radiobuttons != null) {
			for(int i =0 ; i< radiobuttons.size(); i++) {
				radiobuttons.get(i).setEnabled(false);
				radiobuttons.get(i).setFocusable(false);
			}
		}

	}
	
	public void setYearIndex(int index) {
		yearCombo.removeActionListener(this);
		yearCombo.setSelectedIndex(index);
		yearCombo.addActionListener(this);
	}

	public void setMonthIndex(int index) {
		monthsCombo.removeActionListener(this);
		monthsCombo.setSelectedIndex(index);
		monthsCombo.addActionListener(this);
	}
	
	public void setDayIndex(int index) {
		daysCombo.removeActionListener(this);
		daysCombo.setSelectedIndex(index);
		daysCombo.addActionListener(this);
	}
	/*
	public void updateStatusAfterConfirmar() {
		daysCombo.setEnabled(false);
		glassPanel.setVisible(true);

		if(tablescrollpane!=null) {
			tablescrollpane.setHorizontalScrollBarPolicy(HORIZONTAL_SCROLLBAR_NEVER);
			tablescrollpane.setVerticalScrollBarPolicy(VERTICAL_SCROLLBAR_NEVER);

		}

		buttonPanel.setEnabled(false);
		if(mostrarButton!=null) {
			//mostrarButton.setEnabled(false);
		}
		if(monthsCombo!=null) {
			monthsCombo.setEnabled(false);
		}
		if(yearCombo!=null) {
			yearCombo.setEnabled(false);
		}
		if(daysCombo!=null) {
			daysCombo.setEnabled(false);
		}
		if(agregarloteButton!=null) {
			agregarloteButton.setEnabled(false);
		}
		if(modificarloteButton!=null) {
			modificarloteButton.setEnabled(false);
		}
		if(eliminarloteButton!=null) {
			eliminarloteButton.setEnabled(false);
		}
		if(verificarPlanButton!=null) {
			verificarPlanButton.setEnabled(false);
		}
		if(databaseButton!=null) {
			databaseButton.setEnabled(false);
		}

		if(radiobuttons != null) {
			for(int i =0 ; i< radiobuttons.size(); i++) {
				radiobuttons.get(i).setEnabled(false);
				radiobuttons.get(i).setFocusable(false);
			}
		}

	}*/




}
